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

时间:2018-07-12 09:12:21

标签: javascript angular angular5 angular2-services angular4-forms

为什么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);
    }

1 个答案:

答案 0 :(得分:0)

我建议创建一个Observable来获取本地的最后一个值(如果有),否则更新本地存储后的服务器值:

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

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$即可从本地存储(如果有)或从服务器获取菜单列表。