2017-04-12 113 views
0

我有一個帶有子路由的父組件。我想要做的是在它們之間共享一個項目變量。項目的價值可以改變,當它改變時,我需要更新所有的路線頁面。我一直在關注如何實現這一目標的anuglar2 tutorial。但是,當我第一次安裝調用我的observable時,出現問題。當我第一次調用它時,該值不會顯示,但是,當我更新它時,該值將顯示。我一直無法弄清楚爲什麼項目變量最初沒有價值。任何人都知道這是爲什麼以及如何解決它?Angular2 - 服務初始呼叫爲空

父路由(如果項目可以設置和更新)

onSubmit(value: any, valid: any) { 
    if (valid) { 
     // http request to get project 
     this.ad.searchProject(value) 
      .subscribe(
      response => { 
       // If projet found set value in service 
       this.ad.setProject(response); 
       // navigate to child rotue 
       this.router.navigate(['./project'], { relativeTo: this.route }); 
      }, 
      error => { 
       console.log(error) 
      }, 
      () => { 
       console.log("Project Loaded"); 
      } 
      ); 
    } 
} 

項目service.ts

@Injectable() 
export class ProjectService { 
    public project: Project; 
    // Observable string sources 
    private projectSource = new Subject<Project>(); 
    // Observable string streams 
    projectListener$ = this.projectSource.asObservable(); 
    constructor(private http: Http) { 
    } 
    searchProject(value: string): Observable<any> { 
     return this.http.post('/controller/Project/SearchProject', { value: value }, { headers: headers }) 
      .map(response => response.json()); 
    } 
    // Service message commands 
    setProject(project: Project) { 
     this.projectSource.next(project); 
     console.log("call setProject"); 
    } 
} 

孩子航線

export class ChildComponent { 
    project: Project = null; 
    subscription: Subscription; 
    constructor(private ad: ProjectService) { 
     console.log("call child route"); 
     this.subscription = this.ad.projectListener$.subscribe(
      value => { 
       // Called after second value is entered 
       console.log("call subscription"); 
       console.log(value); 
       this.project = value; 
      }); 
    } 
} 

的console.log

[HMR] connected 
call parent route 
Gravity_Project 
setProject 
Project Loaded 
call child route 
// done with first project entry 
Waves Project 
call subscription 
Object {id: 1001, typeID: 45004, studentID: 10000…} 
call setProject 
Project Loaded 
// done with second project entry 

回答

1

答案是行爲主體(https://hassantariqblog.wordpress.com/2016/12/03/angular2-difference-between-a-behavior-subject-and-an-observable/

「的行爲主體是一個類型的題目,主題是一種特殊類型的可觀察到的,所以你可以訂閱郵件像任何其他觀察到的。行爲主體的獨特功能如下:

行爲主題需要一個初始值,因爲它必須始終返回訂閱上的值,即使它未收到下一個() 訂閱時,它會返回上一個值學科。只有在任何時候收到onnext 時,常規觀察值纔會觸發,您可以使用getValue()方法檢索不可觀察代碼中主題的最後一個值。

+0

謝謝。角度文檔應包含您的解釋。 – John

+0

我很高興提供幫助 –