我有一个 Angular 网站,它向控制台报告错误消息,但它在屏幕上运行。我怀疑这是由于页面渲染方式造成的,但在谷歌搜索错误和 Angular 渲染后,我看不到如何修复它。
这是处理 API 调用的服务:
import { Injectable } from '@angular/core';
import { Http, Response, Headers } from "@angular/http";
@Injectable()
export class WmApiService {
private _baseUrl = "http://localhost:58061/";
tempuser = "WebDevelopWolf";
modules: any;
constructor(private _http: Http) {
console.log('Wavemaker API Initialized...');
}
// On successful API call
private extractData(res: Response) {
let body = res.json();
return body || {};
}
// On Error in API Call
private handleError(error: any): Promise<any> {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
// Basic Get W/ No Body
getService(url: string): Promise<any> {
return this._http
.get(this._baseUrl + url)
.toPromise()
.then(this.extractData)
.catch(this.handleError);
}
// Basic Post W/ Body
postService(url: string, body: any): Promise<any> {
console.log(body);
let headers = new Headers({'Content-Type': 'application/json'});
return this._http
.post(this._baseUrl + url, body, {headers: headers})
.toPromise()
.then(this.extractData)
.catch(this.handleError);
}
}
最后是对服务的调用:
ngOnInit() {
this.getUserProfile();
}
// Fill the user profile information
getUserProfile() {
this._wmapi
.getService("User/" + this._wmapi.tempuser)
.then((result) => {
// Push the user to UI
this.userProfile = result;
// Set the user avatar
this.userAvatar = "../assets/users/profile/" + this.userProfile.Username + ".png";
})
.catch(error => console.log(error));
}
过去有几个人告诉我,我不应该使用 Promise,因为它们已经过时了,但这正是几年前使用 Ionic 时所熟悉的 - 然而,如果有的话是一种更好的方法,我绝对愿意接受建议,特别是如果是导致问题的 promise 。
最佳答案
尝试:
<div>{{some-value?.UserFullName}}</div>
在 API 响应到达之前,您的 some-value
对象没有值。然后使用 ?
应用空检查,直到响应到达。
关于javascript - API 调用时的 Angular 定位控制台错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51946994/