解决 Angular 中的错误:ERROR Error : “[object Object]”

5

我非常新于Angular(版本6.1.2),所以请耐心等待。我正在整修ngSpotify应用程序,您可以在Youtube上找到它,但是我卡在浏览器控制台中出现的此错误。

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() {  }

}
2个回答

1

你的catchError没有正确定义,请将其更改为以下内容:

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

奇怪的是,即使TypeScript也应该警告发送错误参数到handleError方法。
最好还是继续使用可观察对象,而不是混合使用promise和可观察对象:
private handleError(error: any): Observable<any> {
  console.error('An error occurred', error); // for demo purposes only
  return of(error.message || error);
}

我在管道中的第一件事就是捕获组件中的错误,但控制台仍然会显示那个晦涩的错误信息。 .pipe(catchError((e) => this.handleError(e)), map(res => res.json()) );我尝试使用tap(res => this.log('whatever'))进行调试,但它抱怨“Property 'log' does not exist on type 'SpotifyService'”。如果我使用tap(res => console.log(this)),控制台不会有任何变化。我尝试在服务中捕获同样的错误,但我甚至无法在服务中使用console.log(this.searchUrl)。这个错误是发生在哪里呢? - aless80

1

我发现了问题。我没有加载HttpModule模块。我在app.module.ts中添加了以下内容:

import { HttpModule } from '@angular/http'; //NEW
..
@NgModule({
  imports: [
          ..
          HttpModule //NEW

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接