从组件ngOnInit调用异步函数订阅

时间:2018-03-29 12:34:15

标签: angular typescript angular2-routing

从我的服务获取数据,不等待服务完成。

下面是为我的网格获取数据的Component,问题是这部分this.store.loadRequestHistory(this.id),当在商店上悬停时没有来自项目的数据。

export class HistoryGridComponent implements OnInit {

  id: number;

 constructor(private route: ActivatedRoute, 
             private router: Router, 
             public store: HistoryStore) {
  }


  ngOnInit() {
      this.route.paramMap
          .map((params: ParamMap) => params.get('id'))
          .subscribe(id => {
              this.id = parseInt(id, 10);
              let list =  this.store.loadRequestHistory(this.id); // I need my data here 
          });
  }

以下是来自服务/商店的方法。这样可以毫无问题地获得数据。

 @action public async loadRequestHistory(requestId: number): Subscription {
        this.loading = true;
        let history = new HistoryClient(this.http, environment.apiUrl);
        let response = history.getRequestHistory(requestId);
        return response.subscribe(
            (data) => {
                try {
                    this.items = _(data)
                        .map(historySummaryMapper.map)
                        .value();

                    this.itemCount = data.length;

                    this.loading = false;
                }
                catch (error) {
                    console.log(error);
                    this.loading = false;
                }


            },
            (error) => {
                console.log(error);
                this.loading = false;
            },
            () => {
                 this.loading = false;
            }
        );
    }

1 个答案:

答案 0 :(得分:0)

试试这个,使用async / await并返回observable

 ngOnInit() {
      this.route.paramMap
          .map((params: ParamMap) => params.get('id'))
          .subscribe(async id => {
              this.id = parseInt(id, 10);

        let list=  await this.store.loadRequestHistory(this.id).toPromise();// I need my data here 

          });
  }


 public loadRequestHistory(requestId: number): Observable<any> {
        this.loading = true;
        let history = new HistoryClient(this.http, environment.apiUrl);
        let response = history.getRequestHistory(requestId);
        return response;
   }