Angular2函数在服务中未定义
Angular2 function in a service undefined
我尝试从组件(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(…)
有人能帮我解决这个问题吗?谢谢! 您需要使用statusChangeCallback
将this
绑定到适当的上下文中
FB.login(this.statusChangeCallback.bind(this),
或使statusChangeCallback
为箭头函数
statusChangeCallback = (response) => {
相关文章:
- Ember服务在注入组件并在计算属性中使用后是未定义的
- 未定义服务
- Http服务工厂将未定义的返回到Angular中的控制器
- 角度服务未定义
- 通过C#向区块链服务发送请求时未定义XMLHttpRequest
- 服务变量分配了数据,但在访问时始终未定义
- 承诺返回未定义的服务
- 从服务返回值时$scope控制器的变量是未定义的
- 提供“角服务”;TypeError:无法读取属性'helloConsole'“未定义”;
- 正在从web服务接收未定义的信息
- Angular 1.5.4服务未定义
- Angularjs自定义服务变量未被$http成功定义
- 使用路由的未定义服务控制器
- Web服务返回给javascript的值是未定义的
- 返回未定义的角度服务不是一个函数
- 无法使用服务AngularJS - “无法读取未定义的属性'原型'”
- 服务函数返回未定义
- 类型错误:parsed 在 angularjs 服务单元测试中未定义
- 尽管注入了$http,但它在服务中是未定义的
- GAS库和WebApp权限[ReferenceError:未定义“服务”.]