json Angular 4 - 错误类型错误,错误上下文 DebugContext_

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44879095/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:57:36  来源:igfitidea点击:

Angular 4 - ERROR TypeError, ERROR CONTEXT DebugContext_

jsonangulartypescriptobservable

提问by rafalrafal

I'm rookie in Angular 4 and I need some help. My code in console display error but in my template everything display correct. Could someone help me understand what happend?

我是 Angular 4 的新手,我需要一些帮助。我在控制台中的代码显示错误,但在我的模板中,一切都显示正确。有人能帮我理解发生了什么吗?

Error

错误

ERROR TypeError: Cannot read property 'Tytul' of undefined
NewsDetailsComponent.html:7 ERROR CONTEXT DebugContext_ {view: Object, nodeIndex: 12, nodeDef: Object, elDef: Object, elView: Object}

news.ts

新闻.ts

export interface News {
Ident: number;
Tytul: string;
Tresc: string;
Data: string;

}

}

news.service.ts

新闻服务.ts

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';

import { News } from './news';

@Injectable()

export class NewsService {

private newsUrl = 'http://localhost:6128/getnews';
private headers = new Headers({ 'Content-type': 'application/x-www-form-urlencoded' });
private options = new RequestOptions({ headers: this.headers, withCredentials: true });

constructor(private http: Http) {}

getNews(): Promise<News[]> {

    return this.http.get(this.newsUrl, this.options)
        .toPromise()
        .then(response => response.json().data as News[])
        .catch(this.handleError);
}

getOneNews(id: number) {

    const url = `${this.newsUrl}?Ident=${id}`;
    return this.http.get(url, this.options)
        .map(res => res.json());
}       

private handleError(error: any): Promise<any> {

    console.error('An error occurred', error);
    return Promise.reject(error.message || error);
}

}

news-details.component.ts

新闻细节.component.ts

import { Component, Input, OnInit } from '@angular/core';
import { ActivatedRoute, Params }   from '@angular/router';
import { Location }                 from '@angular/common'; 
import 'rxjs/Rx';
import 'rxjs/add/operator/switchMap';

import { News }                     from './news';
import { NewsService }              from './news.service';

@Component({
selector: 'app-news-details',
templateUrl: './views/news-details.component.html',
providers: [NewsService]
})

export class NewsDetailsComponent implements OnInit  { 

@Input() news: News;

constructor(
    private newsService: NewsService,
    private route: ActivatedRoute,
    private location: Location
) {}

ngOnInit(): void {

    this.route.params
        .switchMap((params: Params) => this.newsService.getOneNews(+params['id']))
        .subscribe(res => this.news = res);
}

goBack(): void {
    this.location.back();
}
}

news-details.component.html

新闻细节.component.html

<section class="header-box">
    <button class="header-btn back icon-wroc" (click)="goBack();"></button>
    <div class="header-title">Komunikat</div>
</section>
<section class="content-box">
    <h2>{{ news.Tytul }} </h2>
    <div class="content-content" [innerHTML]="news.Tresc"></div>
</section>

回答by Volodymyr Bilyachat

You are doing request to service which probably get data from the server. The problem is simple that while you are doing request to server your object is null but view is already generated you have two options First

您正在请求可能从服务器获取数据的服务。问题很简单,当您向服务器发出请求时,您的对象为空,但视图已经生成,您有两个选择首先

 <h2>{{ news?.Tytul }} </h2>

Second

第二

<section class="content-box" *ngIf="news">
    <h2>{{ news.Tytul }} </h2>
    <div class="content-content" [innerHTML]="news.Tresc"></div>
</section>

Fist option will generate empty h1 and div, second option will not generate anything untill news is not null

第一个选项会生成空的 h1 和 div,第二个选项不会生成任何东西,直到 news 不为空