Angular2函数在服务中未定义

Angular2 function in a service undefined

本文关键字:未定义 服务 函数 Angular2      更新时间:2023-09-26

我尝试从组件(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);
  }
 }

in my 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(…)
有人能帮我解决这个问题吗?谢谢!

您需要使用statusChangeCallbackthis绑定到适当的上下文中

FB.login(this.statusChangeCallback.bind(this),

或使statusChangeCallback为箭头函数

statusChangeCallback = (response) => {