Angular服务仅在页面刷新时返回数据

问题描述 投票:0回答:1

为什么this.menulist甚至空了?

layout.component.ts

 ngOnInit() {


    this.menulist = localStorage.getItem('menulist');  

    if (this.menulist) {

    } else {
      this.SetMenuList(); // Else call the service and sort the menu then
    }
     this.menulist = localStorage.getItem('menulist'); // null even after calling  SetMenulist
     this.jsonmenulist = JSON.parse(this.menulist); 
    } 

    SetMenuList() {
        this._UserspecificmenuaccessService.getRMA("driver")
      .map((lst) => {
        if (lst && lst.length > 0) {
          console.log(lst);
          localStorage.setItem('menulist', JSON.stringify(lst));
          this.menulist = localStorage.getItem('menulist'); this.jsonmenulist = JSON.parse(this.menulist);          

        }
      }, (error) => {
        console.error(error)
      });
  }

服务方式:

  getRMA(Id:any): Observable<Imstmenu[]> {
     return this._http.get("http://172.19.32.235:3000/api/USMA/selectAll/"+Id+"")
    .map((response: Response) => {<Imstmenu[]>response.json(); 
    .catch(this.handleError);
    }
javascript angular angular5 angular2-services angular4-forms
1个回答
0
投票

我建议创建一个Observable,从本地获取最后一个值(如果可用),否则更新localstorage后的服务器值:

updateMenuListOnce$是一个Observable,它将调用服务器,更新localstorage并返回新值:

const updateMenuListOnce$ = 
  this._UserspecificmenuaccessService.getRMA("driver")
  .pipe(first(), 
   tap(menuList => localStorage.setItem('menulist', JSON.stringify(menuList)));

如果可用,menuList$ Observable将返回localstorage中的值,或者订阅之前声明的Observable

this.menuList$ = of(localStorage.getItem('menulist'))
.pipe(exhaustMap(menuList => 
   menuList ? of(<Imstmenu[]>menuList) : updateMenuListOnce$));

现在您只需订阅menuList$即可从localstorage获取菜单列表(如果可用)或从服务器获取。

© www.soinside.com 2019 - 2024. All rights reserved.