鍍金池/ 問(wèn)答/HTML5/ ng6 behavSubject問(wèn)題

ng6 behavSubject問(wèn)題

現(xiàn)在,在做一個(gè)登錄之后,根據(jù)登錄人,動(dòng)態(tài)傳遞菜單數(shù)據(jù),并生成菜單。所以本人使用rxjs寫(xiě)了一個(gè)全局服務(wù),其中setMenu()是在登錄后,將數(shù)據(jù)set進(jìn)服務(wù)中,getMenu()是在sidebar中,拿到相應(yīng)的菜單數(shù)據(jù)。

import { Injectable,OnInit } from '@angular/core';
import {BehaviorSubject} from "rxjs";

@Injectable()
export class BehaviorService implements OnInit{
    menuBehavior:any;
    menuData:any;

    constructor() {
        this.menuBehavior=new BehaviorSubject(null);
    }

    ngOnInit(){

    }

    setMenu(menuData){
            console.log("設(shè)置數(shù)據(jù)");
            this.menuBehavior.next(menuData);
            console.log(this.menuBehavior);//已經(jīng)獲取到菜單數(shù)據(jù)了
    }
    getMenu(){
            return this.menuBehavior;//此時(shí),卻還是初始值
    }
}

但是,在sidebar中,訂閱的時(shí)候,得到的確實(shí) null,我很奇怪,明明在setMenu時(shí)已經(jīng)在流中,
注入了 菜單數(shù)據(jù),為什么訂閱的時(shí)候,不行呢?

ngOnInit() { 

    this.menuService.getMenu().subscribe((v)=>{
      console.log(v);// null  而不是 菜單數(shù)據(jù)
      this.data=v;
      this.allData=v
    });
  }
回答
編輯回答
骨殘心

建議你打斷點(diǎn)查看this.menuBehavior.next(menuData);this.menuService.getMenu().subscribe((v)=>{ 的執(zhí)行順序

2018年4月14日 02:56
編輯回答
未命名

跟順序無(wú)關(guān)。重點(diǎn)是你是否在哪里手動(dòng)進(jìn)行了setMenu ? 如果沒(méi)有的話,只是初始化的數(shù)據(jù)

2018年4月18日 10:44