網站搜尋

typescript - Angular 6 如何在 App 元件加載之前加載服務?


我正在我的資料服務中獲取 JSON 物件的值,但在我的資料服務加載之前,所有組件都已經加載。因此,當我從組件中調用服務方法時,我得到的是未定義的值。

答案#1

我猜您正在使用路由器來訪問您的頁面,因此您可以簡單地使用「resolver」功能:RouterLink 描述。

path: 'app', component: AppPage, resolve: { myData : DataResolve }

在這裡,我們請求使用解析器 DataResolve 來解析變數 "myData"。DataResolve 是一個實現了 Resolve 介面的簡單可注入類(Injectable):

import { Resolve } from '@angular/router';
import { Injectable } from '@angular/core';

@Injectable()
export class UserResolve implements Resolve<any> {

  constructor(private myService: MyService) {}

  async resolve() {
    const myData= await this.myService.getMyData().toPromise();
    return myData;
  }

}

然後當值被解析後,元件將會載入。你可以從 ActivatedRoute 獲取你的資料:

 import { ActivatedRoute } from '@angular/router';

 constructor(private route: ActivatedRoute {
    this.route.data.subscribe(() => {
      this.data = this.route.snapshot.data.myData;
    });
  }

答案#2

您可以在您的資料服務中使用解析器:

  1. 在你的路由中,你可以加入 resolve 屬性。
  2. 在您的服務中實現 resolve 介面,並新增一個 resolve 方法。
  3. 只需在你的組件中訂閱可觀察服務即可。

參考 angular.io