我正在尝试为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模板中应用'async'管道,但似乎这不起作用。
可能是什么原因?谢谢!
答案 0 :(得分:3)
您还需要为此代码使用异步管道
<div *ngIf='exerciseList && exerciseList.length > 0'>
将其更改为
<div *ngIf='(exerciseList | async)?.length > 0'>
答案 1 :(得分:0)
如果您使用Observables
呼叫任何API,则必须订阅它才能拨打电话。如果您没有.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