ค้นหาเว็บไซต์

typescript - angular async pipe, ข้อมูลไม่เติมในเทมเพลต


ฉันกำลังพยายามใช้ async pipe สำหรับแอป 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);
    }
}

ส่วนประกอบการออกกำลังกายด้านซ้าย:

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

เอชทีเอ็มแอล:

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

ฉันใช้ pipe 'async' ในเทมเพลต HTML แต่ดูเหมือนว่านี่จะไม่ทำงาน

สาเหตุอาจเกิดจากอะไร? ขอบคุณ!

คำตอบ #1

คุณยังต้องใช้ async pipe สำหรับโค้ดนี้ด้วย

<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