javascript - API 调用时的 Angular 定位控制台错误

标签 javascript angular typescript

我有一个 Angular 网站,它向控制台报告错误消息,但它在屏幕上运行。我怀疑这是由于页面渲染方式造成的,但在谷歌搜索错误和 Angular 渲染后,我看不到如何修复它。

控制台的外观如下: enter image description here

这是处理 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/

相关文章:

javascript - 在 Angular Material 中关闭多选下拉菜单时触发事件

javascript - 通过计算将对象数组转换为数组

angular - Angular 10 的 ng 测试在 gitlab ci 中挂起

javascript - redux-saga-test-plan expectSaga- 使用状态分支测试 reducer

javascript - Angular 6 每 5 秒运行一次代码,但它第一次发出

javascript - symfony2 + Assets : how to restrict a css to a print when using {% javascripts %}

javascript - 使用环境变量动态更改 Angular 6 中的样式

javascript - 从一个组件更改变量或从另一个组件调用函数

Angular 2 和谷歌自定义搜索。 Angular2剥离html标签

angular - 如何在 Angular 2 的另一个组件中导入类?