【问题标题】:Call service after other service finishes in Angular在其他服务在 Angular 中完成后调用服务
【发布时间】:2020-03-29 15:57:28
【问题描述】:

我在 Angular 的组件上有以下内容:

notifier: Subscription;

ngOnInit() {

  this.authService.init();

  this.notifier = this.noteService.get().subscribe((note: Note) => { 

    if (note.code == 1) {
      this.authService.init();
    }

  });

}

authService.init() 结束从我需要调用的数据库中获取数据后:

this.noteService.send(2);  

authService如下:

export class AuthorizationService {

  private data$: Observable<Data[]>;

  init() {
    this.data$ = this.httpClient.get<Data[]>>(`auth/data`);
  }

}

我应该怎么做?

【问题讨论】:

  • 为什么不创建第二个服务的实例并在完成其逻辑后或在 ngOnDestroy() 方法中使用它在第一个服务中,或者您可以使用一个简单的变量来引用第一个服务完成任务了吗?

标签: angular angular8 angular-observable


【解决方案1】:

您应该使用flatMap 来连接请求。

但首先我建议您像这样更改 AuthorizationService 中的 init() 方法:

export class AuthorizationService {

  private data$: Observable<Data[]>;

  init(): Observable<Data[]> {
    return this.httpClient.get<Data[]>>(`auth/data`);
  }

}

然后在你的组件中:

notifier: Subscription;

ngOnInit() {
      this.authService.init().pipe(flatMap(() => this.noteService.send(2))).subscribe(
        () => {
           // Success of this.noteService.send(2)
        }
     );

  });

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-27
    • 2011-05-04
    相关资源
    最近更新 更多