我在一个组件中有一个http调用,通常需要5-10分钟的时间来处理。在这个http呼叫期间,我希望确保所有其他路由器链路按照它们的正常行为工作。当我从这个组件切换到另一个组件时,所有组件都会为这个http调用处理列表,当这个http处理完成后,我想向用户显示一个通知,说明分析已经完成。
发布于 2018-08-16 11:40:42
您可以从服务进行调用,并让应该在服务完成时得到通知的组件订阅该服务的可观察性。
发布于 2018-08-16 12:36:26
根据向用户显示通知的首选方法,可以以不同的方式完成这一任务。
选项1组件驱动
将长时间http调用的执行移动到服务
@Injectable()
export class MyService {
onNotificationRecieved: Subject<any>;
constructor(private http: HttpClient) {
}
myLongHttpCall() {
this.http.get('myurl').subscribe(result => {
this.onNotificationRecieved.next(result);
}, err => {
//Handle error
});
}
}
并让活动组件监听结果。
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnDestroy {
private _unsubscribe: Subject<any>;
constructor(private myService: MyService) {
this._unsubscribe = new Subject();
myService.onNotificationRecieved.pipe(takeUntil(this._unsubscribe)).subscribe(result => {
//Show notification to user
});
}
ngOnDestroy(): void {
// Unsubscribe from subscription
this._unsubscribe.next();
this._unsubscribe.complete();
}
}
选项2--服务驱动(例如,使用to通知)--将所有元素保留在服务中,这意味着您不必担心当前显示的组件是哪个
@Injectable()
export class MyService {
constructor(private http: HttpClient, private snackBar: MatSnackBar) {
}
myLongHttpCall() {
this.http.get('myurl').subscribe(result => {
let config = new MatSnackBarConfig();
this.snackBar.open('Your Notification Message', 'Dismiss', config);
}, err => {
//Handle fail
});
}
}
https://stackoverflow.com/questions/51876127
复制相似问题