angular2访问并将服务返回的对象属性分配给组件局部变量

时间:2017-03-04 20:57:22

标签: angular typescript

我的视频服务:

public getExercise(exerciseId): Observable<Exercise[]>{

        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers, withCredentials: true });

        return this.http.get(this.base_url + exerciseId + '/', options)
        .map(this.extractData)
        .catch(this.handleError);
}

在我的模板中,我有:

<!-- Show current level -->
<div align="center">
 <h6>Ihre aktuelle Intensitätsstufe ist {{intensity_level}}</h6>
</div>

<div *ngIf="showVideo" align="center" class="video-container">
        <iframe [src]="exercise_video_url | safe" frameborder="0" allowfullscreen></iframe>
</div>

我的组件:

export class VideoPage implements OnInit {

    exercise: Exercise[];
    errorMessage: string;

    public exercise_id: number;
    public intensity_level: number;
    public rating: number;
    public exercise_video_url: string;
    public current_date: string;


    constructor(public navCtrl: NavController, public navParams: NavParams, public videoService: VideoService) {

        console.log(this.navParams.get('exerciseId'));
        this.exercise_video_url='';

        this.exercise_id=this.navParams.get('exerciseId');

    }

    ngOnInit(){

        this.getExercise()
    }

    getExercise(){

        this.videoService.getExercise(this.exercise_id)
        .subscribe(
            exercise => {
                this.exercise = exercise;
                console.log(this.exercise[0].video_url)

            },
            error => {
                this.errorMessage = <any>error;
            });

        this.exercise_video_url=this.exercise[0].video_url;

    }   
}

但是,对象属性未分配给我的本地变量,因此我可以将它们绑定在模板上。我的服务只返回一个对象,这就是我使用this.exercise[0]的原因,如果我尝试在get()之外编写相同的行,则会出现编译错误(这看起来很明显)。这应该做什么?

控制台行打印网址。

2 个答案:

答案 0 :(得分:1)

此处的问题是您要在subscribe功能之外分配视频网址。

getExercise(){

    this.videoService.getExercise(this.exercise_id)
    .subscribe(
        exercise => {
            this.exercise = exercise;
            console.log(this.exercise[0].video_url)
            // NEW LINE
            this.exercise_video_url=this.exercise[0].video_url;
        },
        error => {
            this.errorMessage = <any>error;
        });

    // OLD LINE
    // this.exercise_video_url=this.exercise[0].video_url;

}   

答案 1 :(得分:0)

您没有将响应内容映射到所需的练习模型, 修改您的服务,如下所示

public getExercise(exerciseId): Observable<Exercise[]>{

        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers, withCredentials: true });

        return this.http.get(this.base_url + exerciseId + '/', options)
        .map((response: Response) => <Exercise[]>response.json())
        .catch(this.handleError);
}