无法访问HTTP响应

时间:2016-09-18 17:07:04

标签: angular typescript angular2-http angular-template

我从HTTP响应中获得了这些数据

{
"files": [ ],
"posts": [
    {
        "content": "Dies ist ein Test-Posting, das zum Projekt 2 gehört.",
        "id": 2,
        "name": "Beispiel Post 2",
        "timestamp": "Wed, 10 Aug 2016 19:52:09 GMT"
    }
],
"project": {
    "id": 2,
    "info": "Dies ist der Text für das Beispiel Projekt 2",
    "name": "Beispiel Projekt 2",
    "timestamp": "Wed, 10 Aug 2016 19:50:59 GMT"
    }
}  

它存储在组件变量中,现在我想在我的模板中访问它。我试着做这样的事情:

{{project.project.id}}  

它不起作用。对象存储如下:

Object { files: Array[0], posts: Array[1], project: Object }  

我已经尝试过这样的解决方案:iteration a json object on Ngfor in angular 2但它不会有帮助。

继承了我得到的例外:
Uncaught (in promise): Error: Error in ./ProjectDetailComponent class ProjectDetailComponent - inline template:0:4 caused by: self.context.project is undefined

有关详细信息,请参阅以下文件:

组件:

@Component({
    selector: 'app-project-detail',
    templateUrl: './project-detail.component.html',
    styleUrls: ['./project-detail.component.sass']
})
    export class ProjectDetailComponent implements OnInit {
    private project;
    private errorMessage;

    constructor(private route: ActivatedRoute,
                private router: Router,
                private projectService: ProjectsService) {
    }

    ngOnInit() {
        this.route.params.forEach((params: Params) => {
            let id = +params['id'];
            this.projectService.getProjects(id).subscribe(
                function (project) {
                    this.project = project;
                },
                error => this.errorMessage = <any>error
            );
        });
    }

}  

服务:

@Injectable()
export class ProjectsService {

    constructor(private http: Http) {}

    private projectsUrl = 'http://localhost:2000/api/projects/';

    getProjects(id?: number): Observable<any>{
        if(id){
            return this.http.get(this.projectsUrl + ""+id)
                .map(this.extractData)
                .catch(this.handleError);
        } else {
            return this.http.get(this.projectsUrl)
                .map(this.extractData)
                .catch(this.handleError);
        }


    }

    private extractData(res: Response) {
        let body = res.json();
        return body;
    }
    private handleError (error: any) {
        // In a real world app, we might use a remote logging infrastructure
        // We'd also dig deeper into the error to get a better message
        let errMsg = (error.message) ? error.message :
            error.status ? `${error.status} - ${error.statusText}` : 'Server error';
        console.error(errMsg); // log to console instead
        return Observable.throw(errMsg);
    }
}

我感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

该值未分配到您所处的位置。

ngOnInit() {
    this.route.params.forEach((params: Params) => {
        let id = +params['id'];
        this.projectService.getProjects(id).subscribe(

            // function (project) {
            // should be
            (project) => {             // <<<<=== change
                this.project = project;
            },
            error => this.errorMessage = <any>error
        );
    });
}

并将其与

一起使用
{{project?.project?.id}}