Angular2和TypeScript中属性未定义

5

我希望通过使用Angular2模块Http来检索本地json文件的内容。

我得到的错误是一个未定义属性,但我认为它应该在Observable/Subscribe调用prepareCredentials函数时被初始化。

以下是错误信息:

TypeError: Cannot read property 'clientId' of undefined
    at SpotifyComponent.prepareCredentials (spotify.component.ts:58)
    at SafeSubscriber.eval [as _complete] (spotify.component.ts:38)
    at SafeSubscriber.__tryOrUnsub (Subscriber.ts:240)
    at SafeSubscriber.complete (Subscriber.ts:226)
    at Subscriber._complete (Subscriber.ts:142)
    at Subscriber.complete (Subscriber.ts:120)
    at MapSubscriber.Subscriber._complete (Subscriber.ts:142)
    at MapSubscriber.Subscriber.complete (Subscriber.ts:120)
    at XMLHttpRequest.onLoad (xhr_backend.ts:67)
    at ZoneDelegate.invokeTask (zone.js:356)

组件,
import { Component, OnInit } from '@angular/core';
import { Http, Response } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

import { SpotifyService } from './spotify.service';

@Component({
  moduleId: module.id,
  selector: 'app-spotify',
  templateUrl: 'spotify.component.html',
  styleUrls: ['spotify.component.css'],
  providers: [SpotifyService]
})

export class SpotifyComponent implements OnInit {
  private credentialsData: {
    clientId: string,
    clientSecret: string
  };

  constructor(
    private http: Http,
    private spotifyService: SpotifyService
  ) { }

  ngOnInit() {
    if (this.spotifyService) {
      this.http.get('../app/data/credentials.json')
        .map(this.handleResponse)
        .subscribe(
          this.setupCredentials,
          this.handleError,
          () => { this.prepareCredentials(); }
        );
    }
  }

  private setupCredentials(subData) {
    console.log('Setting up credentials...');
    this.credentialsData = {
      clientId: <string>subData.clientId,
      clientSecret: <string>subData.clientSecret
    };
    console.log('credentials: ' +
        JSON.stringify(this.credentialsData));
    console.log('credentials clientId: ' +  this.credentialsData.clientId);
    console.log('credentials clientSecret: ' + this.credentialsData.clientSecret);
  }

  private prepareCredentials() {
    console.log('Preparing credentials...');
    this.spotifyService.prepare(
      this.credentialsData.clientId,
      this.credentialsData.clientSecret,
      '', 'http://localhost:4200/spotify');

  }

  private handleResponse(res: Response) {
    console.log(JSON.stringify(res.json()));
    return res.json().spotify;
  }

  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);
  }

}

并且这项服务,

import { Injectable } from '@angular/core';

@Injectable()
export class SpotifyService {
  private clientId: string;
  private clientSecret: string;
  private scopes: string;
  private callbackUrl: string;

  constructor() { }

  wakeUpTest(): string {
    console.log('SpotifyService is awake and initiated.');
    return 'SpotifyService is awake and initiated.';
  }

  prepare(clientId: string,
    clientSecret: string,
    scopes: string,
    callbackUrl: string): void {
        console.log(clientId);
  }

  getAuthCode(): void {
    let authUrl: string = 'https://accounts.spotify.com/authorize' +
      '?response_type=code' +
      '&client_id=' + this.clientId +
      '&scope=' + encodeURIComponent(this.scopes) +
      '&redirect_uri=' + encodeURIComponent(this.callbackUrl);
  }

}

提前感谢您的任何帮助或指导,因为这对我来说都是相对较新的。

1个回答

2
我想你的问题可能在这里:

this.http.get('../app/data/credentials.json')
  .map(this.handleResponse)
  .subscribe(
    this.setupCredentials,  <== 
    this.handleError,
    () => { this.prepareCredentials(); }
  );

如果您直接传递一个方法引用,这是默认的JS/TS行为。您可以使用bind,例如this.setupCredentials.bind(this),或者使用箭头函数来保留this

this.http.get('../app/data/credentials.json')
   .map(this.handleResponse)
   .subscribe(
      (data) => this.setupCredentials(data),
      (res) => this.handleError(res),
      () => { this.prepareCredentials(); }
   );

希望这能对你有所帮助!

这是隐式完成的,我认为是因为在setupCredentials中获取了所有的打印输出?这也是Angular文档中采用的相同做法,仅传递函数以进行隐式数据传递。 - Emil Hammarström
打印 this 给了我一个 SafeSubscriber 对象的输出,像这样 - Emil Hammarström
我需要先道个歉,你提供的解决方案实际上解决了我的问题。这是否与对象的实例化有关?而且,我的情况是否是一个特殊情况,因为Angular2文档最初就是这样做的?无论如何,感谢@yurzui的帮助。 - Emil Hammarström
我能看到一个文档示例的链接,展示这种实践吗? - yurzui
他们只是在map回调函数中不使用this关键字(以这种方式的MapSubscriber)。 - yurzui
显示剩余2条评论

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