在angular 2应用程序的后台/分离线程中执行函数
我正在开发一个应用程序,我有以下要求。从我的angular应用程序中,我正在对服务器进行REST调用,这将触发服务器上的一些作业,并返回状态为“作业已启动”。之后,我希望每10秒检查一次作业的状态,服务器为其提供返回作业状态的API 现在我的要求是每10秒调用一次作业状态API,但在后台,这意味着用户应该能够在应用程序上执行其他任务 我将如何实现这一点在angular 2应用程序的后台/分离线程中执行函数,angular,web-worker,Angular,Web Worker,我正在开发一个应用程序,我有以下要求。从我的angular应用程序中,我正在对服务器进行REST调用,这将触发服务器上的一些作业,并返回状态为“作业已启动”。之后,我希望每10秒检查一次作业的状态,服务器为其提供返回作业状态的API 现在我的要求是每10秒调用一次作业状态API,但在后台,这意味着用户应该能够在应用程序上执行其他任务 我将如何实现这一点 任何有关示例的帮助都会非常有用。您可以通过两种方式解决此问题 最简单的方法-setInterval()。 因为它只是检查作业是否通过http请求
任何有关示例的帮助都会非常有用。您可以通过两种方式解决此问题 最简单的方法-
setInterval()
。
因为它只是检查作业是否通过http
请求完成,所以不会杀死UI
,用户将能够执行其他操作
setInterval(() => {
this.http.post(...).subscribe(
(res) => handleResponse(res);
);
}, 10000);
网络工作者
与网络工作者有很多麻烦,取决于你的项目是如何建立等,但它会做的后台线程技巧,但有一个问题。只是发出http请求来检查web worker需要的某些数据吗?。如果是,那么看看这个,它很好地解释了它是如何工作的。您必须创建XHR
请求,因为Angular
和jQuery
(我不是100%确定,但可能有ajax
用于web工作人员)在那里不起作用。最大的麻烦是加载web worker的源代码。您可以将web worker()的源代码字符串化,也可以将其构建为文件并链接。这取决于你的项目将如何在生产中构建
// source code for worker.
let code = function() {
setInterval(function() {
makeRequest()
.then(function(res) {
// process request. if you want to send message to main thread just use fn below
// message can be almost everything, but it can not pass any methods.
// self is simply worker. you don't have to declar self, it's already declared like window in main thread.
self.postMessage(message)
})
.catch(function(err) {
// process request failure.
})
}, 10000)
};
// stringify source code and make it blob as described in link
let worker = new Worker(code);
worker.addEventListener('message', function(workerReponse) {
// workerReponse is simply `message` which was passed in self.postMessage(message).
})
makeRequest方法可以如下所示您可以使用RxJS observable with timer,以便轻松控制计时器。如果不在页面卸载时销毁计时器,则在页面销毁后也将调用API。在组件文件中,API将每隔10秒调用一次,直到变量alive为true,并且我们在销毁时将其设置为false以停止计时器
组件文件
import { Component } from '@angular/core';
import { AppTestService } from './app-test.service';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/takeWhile';
import 'rxjs/add/observable/timer'
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ],
providers:[ AppTestService ]
})
export class AppComponent {
name = 'Angular 5';
alive = true;
constructor(private appTest : AppTestService) {
Observable.timer(0,10000)
.takeWhile(() => this.alive) // only fires when component is alive
.subscribe(() => {
this.appTest.getData().subscribe(data=> {
console.log(data);
})
});
}
ngOnDestroy(){
this.alive = false; // switches your IntervalObservable off
}
}
服务
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class AppTestService {
constructor(private http:HttpClient) { }
getData(){
return this.http.get('https://jsonplaceholder.typicode.com/users/1');
}
}