Angular 2 HTTP - 无法使用url参数获取数据

时间:2017-04-09 17:00:44

标签: angular

我无法理解为什么这段代码没有设置this.video的值。 这是一个麻烦的组件,我评论错误的位置(video-detail.component.ts):

path

这是我的服务。我不认为这项服务有任何错误。 (video.service.ts):

import 'rxjs/add/operator/switchMap';
import { Component, OnInit }      from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { Location }               from '@angular/common';
import { VideoService } from './video.service';
import { Video } from './video';

@Component({
    selector: 'video-detail',
    providers: [ VideoService ],
    templateUrl: './video-detail.component.html',
    styleUrls: ['./video-detail.component.css']
})
export class VideoDetailComponent implements OnInit {

    video: Video;

    constructor(private videoService: VideoService,
        private route: ActivatedRoute,
        private location: Location) { }

    ngOnInit():void {
        this.route.params
            .switchMap((params:Params) => this.videoService.getVideoByID(params['id']))
            .subscribe(video => {
                console.log('video by id', video); // video exist, I've check it
                this.video = video  // this.video doesn't change, it remain undefined
            });             
    }
}

这对我的InMemoryData来说很有见地:

import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { Video } from './video';

@Injectable()
export class VideoService {
    private headers = new Headers({ 'Content-Type': 'application/json' });
    private listVideosURL = 'api/videos';

    constructor(private http: Http) { }

    getVideoByID(id): Promise<Video> {
        return this.getVideosList().then(videos => videos.find(video => video.id.videoId == id));
    }

    getVideosList(): Promise<Video[]> {
        return this.http.get(this.listVideosURL).toPromise()
            .then(response => {
                console.log('responseJson', response.json().data);
                this.listVid = response.json().data as Video[];
                return response.json().data as Video[];
            })
            .catch(this.handleError);
    }

    private handleError(error: any): Promise<any> {
        console.error('Error Bro!!!', error);
        return Promise.reject(error.message || error);
    }
}

其他一切正常,服务工作,我使用相同的服务来显示所有数据的列表。我使用InMemoryDataService并没有问题 当然,我已经在app.module.ts中设置了所需的所有内容 问题是,为什么订阅(video =&gt; {this.video = video});无法设置视频属性?

0 个答案:

没有答案