如何调用使Angular Service同步?

时间:2018-05-18 06:35:56

标签: javascript angular typescript angular5

我试图从localStorage读取一个项目(menulist)。如果它为null,我正在调用一个服务,该服务将在从数据库中获取menulist后存储menulist)。 似乎服务是异步的,因为我在以下代码中获得了Cannot read property 'sort' of null

ngOnInit() {

    this.menulist = localStorage.getItem('menulist');
    if (!this.menulist) {
      this.SetMenuList();
    }
    this.jsonmenulist = JSON.parse(this.menulist);
    this.jsonmenulist.sort(function (a, b) { 
      return a.mnuposno > b.mnuposno;
    });
    this.jsonmenulist = this.jsonmenulist.sort();
  }

SetMenuList() {
    this._UserspecificmenuaccessService.getRMA("driver")
      .subscribe((lst) => {
        if (lst && lst.length > 0) {
          localStorage.setItem('menulist', JSON.stringify(lst));
          this.menulist = localStorage.getItem('menulist');
          console.log(this.menulist); // gets called after this.jsonmenulist.sort? 
          return true;
        }
      }, (error) => {
        console.error(error)
      });
  }

控制台:

ERROR TypeError: Cannot read property 'sort' of null

[{"mnurecid":"4","mnuid":"menu1","mnuname":"Bin","mnuurl":"/bin/","mnuposno":"1.0","checked":true}, {"mnurecid":"12","mnuid":"menu9","mnuname":"Menu9","mnuurl":"/menu9","mnuposno":"9.0","checked":false}]

3 个答案:

答案 0 :(得分:1)

您可以使用 rxjs library 中的 toPromise()方法返回promise而不是observable。

所以在您的服务中

getRMA(type) {
        return this.http.post(environment.baseURL + '/getmenulist', { drive: 
          type }, this.options).map((response) => response.json()
     ).toPromise().catch(e => {
    console.log(e);
    )}

    }

并在您的组件中使用 async并等待

 async SetMenuList() {
       let response =  await 
        this._UserspecificmenuaccessService.getRMA("driver")
          console.log(response)         
      }

答案 1 :(得分:1)

不完全是关于 async 的问题,您只需在分配之前使用this.menulist即可。只需更改运行代码的方式即可。

ngOnInit() {
    this.menulist = localStorage.getItem('menulist');
    if (this.menulist) {
        this.sortMenuList(); // Sorting the menu if we have menulist already
    } else {
        this.SetMenuList(); // Else call the service and sort the menu then
    }
}

sortMenuList() {
    this.jsonmenulist = JSON.parse(this.menulist);
    this.jsonmenulist.sort(function (a, b) { 
      return a.mnuposno > b.mnuposno;
    });
    this.jsonmenulist = this.jsonmenulist.sort();
}

SetMenuList() {
    this._UserspecificmenuaccessService.getRMA("driver")
      .subscribe((lst) => {
        if (lst && lst.length > 0) {
          localStorage.setItem('menulist', JSON.stringify(lst));
          this.menulist = localStorage.getItem('menulist');
          this.sortMenuList(); // Sorting the menu if we have menulist already
        }
      }, (error) => {
        console.error(error)
      });
  }

顺便说一下,SetMenuList命名应该是setMenuList(建议用于命名)。

答案 2 :(得分:0)

您可以编写需要在subscribe函数内执行的代码,以便仅在异步操作完成后才执行。