服务中的Angular2函数未定义

时间:2016-11-03 04:41:42

标签: javascript angular typescript

我尝试从组件(fb.component.ts)调用服务的函数(在auth.service.ts中为loginFb)。 似乎我导入了所有内容并启动了服务。但仍然得到'loginfb'未定义的错误。 我的auth.service.ts:

import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class AuthService {

 constructor(private http: Http) {}

 loginFb(uid, accessToken): boolean{
   let headers = new Headers();
   headers.append('Content-Type', 'application/json');
   let body = JSON.stringify({"uid":uid,"accessToken": accessToken});
   this.http.post('http://localhost:3002/signinfb',body,{headers:headers})
   .toPromise()
   .then(response => {
      localStorage.setItem('id_token', response.json().id_token);
      return true;
    })
  .catch(this.handleError);
 return false;
}

private handleError(error: any): Promise<any> {
   console.error('An error occurred', error);
   return Promise.reject(error.message || error);
  }
 }

在我的fb.component.ts中:

  import { Component, OnInit } from '@angular/core';
  import { Router } from "@angular/router";
  import { AuthService } from './auth.service';


  declare const FB:any;

  @Component({
    selector: 'facebook-login',
    providers: [AuthService],
    template: `
    <div>
        <button class="btn" (click)="onFacebookLoginClick()">
            Sign in with Facebook
        </button>
    </div>
  `,
  })

  export class FacebookLoginComponent implements OnInit{

    constructor(private authService: AuthService) {
    }
    ngOnInit() {
      FB.init({
            appId      : '234244113643991',
            cookie     : false,
            xfbml      : true,  
            version    : 'v2.7'
        });
    }

    statusChangeCallback(response) {
        if (response.status === 'connected') {
          let uid = response.authResponse.userID;
          let accessToken = response.authResponse.accessToken;
          // window.alert(uid+"|"+accessToken);
          if (this.authService.loginFb(uid,accessToken)){
            window.alert("GOOD!");
          }else{

          }
        }else if (response.status === 'not_authorized') {

        }else {

        }
    }

    onFacebookLoginClick() {
      FB.login(this.statusChangeCallback, 
      {scope: 'public_profile,email,user_friends,'});
    }
  }

我得到了:

  Subscriber.ts:241 Uncaught TypeError: Cannot read property 'loginFb' of undefined(…)

有人可以帮我解决这个问题吗?谢谢!

1 个答案:

答案 0 :(得分:1)

您需要使用this

statusChangeCallback绑定到正确的上下文
FB.login(this.statusChangeCallback.bind(this),

或使statusChangeCallback成为箭头功能

statusChangeCallback = (response) => {