简体   繁体   English

属性未定义Angular2和TypeScript

[英]Property undefined Angular2 and TypeScript

I am trying to retrieve the contents of a local json file through the use of the Angular2 module Http. 我试图通过使用Angular2模块Http检索本地json文件的内容。

The error I am getting is of an undefined property but I reckon it should have been initialized when the prepareCredentials function is called onComplete by the Observable/Subscribe. 我得到的错误是一个未定义的属性,但我认为它应该在Observable / Subscribe调用onComplete的prepareCredentials函数时初始化。

Here follows the Error, 以下是错误,

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)

Component, 零件,

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

}

and the Service, 和服务,

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

}

Thanks in advance for any help or pointers as all this is relatively new for me. 提前感谢任何帮助或指示,因为这对我来说相对较新。

I suppose that your problem is located here: 我想你的问题就在这里:

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

That's default JS/TS behavior if you pass a method reference directly. 如果直接传递方法引用,这是默认的JS / TS行为。 You can either use bind like this.setupCredentials.bind(this) or use arrow function to retain this : 你可以使用像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(); }
   );

Hope it helps you! 希望它能帮到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 TypeScript / Angular2-例外:TypeError:无法读取未定义的属性“ push” - TypeScript / Angular2 - EXCEPTION: TypeError: Cannot read property 'push' of undefined Angular2 - TypeError:无法读取(Typescript)中未定义的属性“Id” - Angular2 - TypeError: Cannot read property 'Id' of undefined in (Typescript) Typescript / Angular2 TypeError:无法读取undefined的属性 - Typescript/Angular2 TypeError: Cannot read property of undefined 无法读取Angular2 Typescript中未定义的属性“值” - Cannot read property 'value' of undefined in Angular2 Typescript 找不到属性angular2和打字稿 - Property not found angular2 and typescript (Angular2 和 Typescript)Angular 的 DatePicker 无法读取未定义的属性“切换” - (Angular2 & Typescript) Angular's DatePicker Cannot read property 'toggle' of undefined angular2 / typescript项目中未定义的变量localforage - undefined variable localforage in angular2/typescript project Angular2,Typescript:数组map()方法:推送嵌套元素。 无法读取未定义的属性“地图” - Angular2,Typescript: array map() method: Pushing nested elements. Cannot read property 'map' of undefined 覆盖Angular2上的JavaScript NAME属性(打字稿) - Override JavaScript NAME property on Angular2 (typescript) Angular2 / Typescript对象和属性绑定到模板 - Angular2/Typescript object and property binding to template
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM