2017-02-24 51 views
1

我正在嘗試爲Angular 2應用程序使用異步管道。角度異步管道,數據未填充模板

下面是不同的服務/組件的代碼,

服務:

export class WorkoutService { 

    constructor(public http: Http) { } 

    getExercises() { 
     return this.http.get(this.collectionsUrl + '/exercises' + this.params) 
      .map((res: Response) => <Exercise[]>res.json()) 
      .catch(WorkoutService.handleError); 
    } 
} 

LeftNavExercisesComponent:

export class LeftNavExercisesComponent implements OnInit { 
    public exerciseList: Observable<Exercise[]>; 

    constructor(
     public workoutService: WorkoutService, 
     public workoutBuilderService: WorkoutBuilderService) { } 

    ngOnInit() { 

     this.exerciseList = this.workoutService.getExercises(); 

     //this.exerciseList.subscribe(data => 
     // console.log(data)); 
    } 

HTML:

<div *ngIf='exerciseList && exerciseList.length > 0'> 
     <div *ngFor="let exercise of exerciseList|async|orderBy:'title'"> 
      <button class="btn btn-info col-sm-12" (click)="addExercise(exercise)">{{exercise.title}}<span class="glyphicon glyphicon-chevron-right"></span></button> 
     </div> 
    </div> 

雖然我使用下面的代碼,我能看到,API調用發生,這是給我回的結果,

this.exerciseList.subscribe(data => console.log(data)); 

但是,存在的情況下沒有API調用,

this.exerciseList = this.workoutService.getExercises(); 

我在html模板中應用'異步'管道,但似乎這是行不通的。

可能是什麼原因?謝謝!

+0

你試過去除'orderBy'管道嗎? – Jai

回答

2

您還需要使用異步管道將此代碼

<div *ngIf='exerciseList && exerciseList.length > 0'> 

將其更改爲

<div *ngIf='(exerciseList | async)?.length > 0'> 
+0

驚人,作品像魅力....謝謝! – user584018

+0

不客氣,很高興聽到你能使它工作:) –

0

如果您打電話給任何API,然後Observables您必須訂閱它才能撥打電話。如果你不是.subscribe()它,將不會有任何呼叫。

總之,我會說它就像(獲取數據,我正在聽)。所以,這就是爲什麼你的第一個例子工作,因爲你訂閱它,而第二個例子沒有。

所以,最終你不得不使用這樣的事情:

this.exerciseList = this.workoutService.getExercises() 
         .subscribe(excercises => excercises); // it triggers the call 

或者這樣說:

this.workoutService.getExercises() 
      .subscribe(excercises => this.exerciseList = excercises); // it triggers the call 
+0

根據最新的文檔,它不像以前那麼多,但仍然很糟糕,https://angular.io/docs/ts/latest/api/common/index/AsyncPipe-pipe.html'async' pipe _subscribe_直接在模板中的'Observable'。 您提到的解決方法對於解決方法是很好的,但它不回答如何使用'async'管道的問題。 –

+0

@AluanHaddad哦!我怎麼錯過了?是的,它在那裏。 – Jai

+0

看起來'orderby'管道是問題。 – Jai