1

我正在尝试从 api 获取 JSON 数据并使用 angular 2 显示其内容。对话组件:

export class ConversationComponent implements OnInit {
    public conversation: any;

    constructor(private conversationsService: ConversationsService,
                private routeParams: RouteParams) { }


    ngOnInit() {
        let id = +this.routeParams.get('id');
        this.conversationsService.getConversation(id)
            .subscribe(
            con => this.conversation = con,
            error => console.log(this.conversation)
            )
    }
}

对话服务:

@Injectable()
export class ConversationsService {

    private url = 'https://dev4.aldensys.com/PrometheusWebAPI/api/Conversations/';
    private token = this.storageService.getAuthorizationToken();

    constructor(private http: Http, private storageService: StorageService) { }

    getConversation(id: number) {
        var headers = new Headers();
        headers.append('Authorization', 'Bearer ' + this.token);
        var options = new RequestOptions({ headers: headers });
        return this.http.get(this.url + id, options)
            .map(res => res.json())
            .catch(this.handleError);
    }

    private handleError(error: any) {
        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);
    }
}

由于某种原因 this.conversation 是未定义的。在将响应映射到服务文件上的 json 后,我尝试立即提醒响应:它显示“对象:对象”

任何帮助都感激不尽。

4

1 回答 1

2

我懂了。您的问题是模板在数据进入之前显示错误。

用这个

{{conversation?.number}}

在 Angular2 中,与 Angular1 相比,这是不可原谅的

这是文档中的参考

于 2016-06-29T19:05:29.750 回答