简体   繁体   English

如何调用使Angular Service同步?

[英]How to call make Angular Service synchronous?

I trying to read an item (menulist) from localStorage . 我试图从localStorage读取一个项目(菜单)。 If it is null, I am calling a service which will store menulist after fetching it from database). 如果为null,则我正在调用一个服务,该服务将从数据库中获取菜单列表后存储该菜单列表。 It seems that service is asynchronous as I am getting Cannot read property 'sort' of null in the following code. 似乎服务是异步的,因为我在以下代码中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)
      });
  }

Console: 安慰:

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}]

You can use toPromise() method from rxjs library to return promise rather than observable. 您可以使用rxjs 库中的 toPromise()方法返回promise,而不是可观察的。

So In your service 所以为您服务

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

    }

and In your component use async and await 在您的组件中使用异步并等待

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

Not exactly about async broblem, you just use the this.menulist before it's assigned. 异步问题不完全相同,您只需在分配它之前使用this.menulist Just change the way you run your codes. 只需更改您运行代码的方式即可。

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)
      });
  }

By the way, SetMenuList naming should be setMenuList (Just recommended for naming). 顺便说一句, SetMenuList命名应为setMenuList (仅建议使用命名)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM