网站搜索

typescript - angular 异步管道,数据未填充到模板中


我正在尝试在 Angular 2 应用程序中使用 async 管道。

以下是不同的服务/组件代码,

服务:

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);
    }
}

左侧导航练习组件:

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' 管道,但似乎它不起作用。

可能的原因是什么?谢谢!

答案#1

你还需要为这段代码使用 async 管道

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

通过将其更改为

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

答案#2

如果你在调用任何 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