首页 > 解决方案 > 排除错误错误:角度中的“[object Object]”

问题描述

我对 Angular(6.1.2 版)非常陌生,所以请多多包涵。我正在翻新您可以在 youtube 中找到的 ngSpotify 应用程序,但我在浏览器控制台中遇到了这个错误。

ERROR Error: "[object Object]"
resolvePromisehttp://localhost:4200/polyfills.js:3136:31resolvePromisehttp://localhost:4200/polyfills.js:3093:17scheduleResolveOrRejecthttp://localhost:4200/polyfills.js:3195:17invokeTaskhttp://localhost:4200/polyfills.js:2743:17onInvokeTaskhttp://localhost:4200/vendor.js:34899:24invokeTaskhttp://localhost:4200/polyfills.js:2742:17runTaskhttp://localhost:4200/polyfills.js:2510:28drainMicroTaskQueuehttp://localhost:4200/polyfills.js:2917:25 core.js:1673
defaultErrorLogger
core.js:1673
./node_modules/@angular/core/fesm5/core.js/ErrorHandler.prototype.handleError
core.js:1719
next
core.js:4319:109
./node_modules/@angular/core/fesm5/core.js/EventEmitter.prototype.subscribe/schedulerFn<
core.js:3555:34
./node_modules/rxjs/_esm5/internal/Subscriber.js/SafeSubscriber.prototype.__tryOrUnsub
Subscriber.js:195
./node_modules/rxjs/_esm5/internal/Subscriber.js/SafeSubscriber.prototype.next
Subscriber.js:133
./node_modules/rxjs/_esm5/internal/Subscriber.js/Subscriber.prototype._next
Subscriber.js:77
./node_modules/rxjs/_esm5/internal/Subscriber.js/Subscriber.prototype.next
Subscriber.js:54
./node_modules/rxjs/_esm5/internal/Subject.js/Subject.prototype.next
Subject.js:47
./node_modules/@angular/core/fesm5/core.js/EventEmitter.prototype.emit
core.js:3539:52
onHandleError/<
core.js:3846:48
./node_modules/zone.js/dist/zone.js/</ZoneDelegate.prototype.invoke
zone.js:388
./node_modules/zone.js/dist/zone.js/</Zone.prototype.run
zone.js:138
./node_modules/@angular/core/fesm5/core.js/NgZone.prototype.runOutsideAngular
core.js:3783
onHandleError
core.js:3846
./node_modules/zone.js/dist/zone.js/</ZoneDelegate.prototype.handleError
zone.js:392
./node_modules/zone.js/dist/zone.js/</Zone.prototype.runGuarded
zone.js:154
_loop_1
zone.js:677
./node_modules/zone.js/dist/zone.js/</</api.microtaskDrainDone
zone.js:686
drainMicroTaskQueue
zone.js:6

如何解决它?如何理解它的来源,并正确捕捉它?我在 Angular 的英雄之旅教程中尝试了 handleError 的代码,但没有成功。我发现了类似的帖子,但这对我没有帮助。也许我必须使用 Observable,或者找到抛出错误的位置。

代码编译。这是我的服务:

import { Injectable } from '@angular/core';
/*
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { HttpClientModule } from '@angular/common/http';
*/
import { map } from 'rxjs/operators';
import {Http, Response, Headers, RequestOptions} from '@angular/http';

import { Observable, of } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class SpotifyService {
  private searchUrl: string;

  constructor(private _http: Http) {

  }

  searchMusic(str: string, type = 'artist') {
    const accessToken = '<my token, which is probably bad to keep here>';
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('Authorization',  'Bearer ' + accessToken);
    let options = new RequestOptions({ headers: headers });
    this.searchUrl = 'https://api.spotify.com/v1/search?query=' + str + '&offset=0&limit=20&type=' + type + '&market=US';
    return this._http.get(this.searchUrl, options)
      .pipe(

    //EDIT: catchError(this.handleError('searchMusic', []),
    tap(res => console.log(this)),
    catchError((e) => this.handleError(e)),
    map(res => res.json())
      );
  }

   /*EDIT: private handleError(error: any): Promise<any> {
    console.error('An error occurred', error); // for demo purposes only
    return Promise.reject(error.message || error);
   }*/
   private handleError(error: any): Promise<any> {
     console.error('An error occurred', error); // for demo purposes only
   return Promise.reject(error.message || error);
   }

}

和调用它的组件:

import {Component, OnInit} from '@angular/core';
import {SpotifyService} from '../spotify.service';

@Component({
  selector: 'search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {

  SearchStr: string;

  constructor(private _spotifyService:SpotifyService) { 
  }

  searchMusic() {
    this._spotifyService.searchMusic(this.SearchStr)
        .subscribe(res => {
          //EDIT: console.log(res.artists.items);
          console.log(res);
        });
  }

  ngOnInit() {  }

}

标签: javascriptangular

解决方案


catchError的定义不正确,请将其更改为:

catchError((e) => this.handleError(e)),

不过很奇怪,因为即使是 TypeScript 也应该警告向 handleError 方法发送错误的参数。

继续使用可观察对象会更好,而不是混合使用承诺和可观察对象:

private handleError(error: any): Observable<any> {
  console.error('An error occurred', error); // for demo purposes only
  return of(error.message || error);
}

推荐阅读