我想将Facebook身份验证用作Angular服务。 使用此代码,我可以登录/注销但是当我登录并刷新页面时,变量 name 和 isUser 也会刷新/重新初始化(据我所知)到Angular生命周期) - 我尝试在ngOnInit中 checkLoginState()来知道用户是否仍然登录,如果他是,我将查询FB API并将再次重新初始化变量的值。但是代码失败了,因为在ngOnInit FB中还没有定义。那么在页面刷新后可以做些什么来保持变量值不变?或者我应该在全局或缓存中保存它们? 谢谢!
FacebookService:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class FacebookService {
constructor() {
if (!window.fbAsyncInit) {
console.log('define');
window.fbAsyncInit = function () {
FB.init({
appId: "...youAppId...",
xfbml: true,
version: 'v2.10'
});
};
}
}
loadAndInitFBSDK(): Observable<any> {
var js,
id = 'facebook-jssdk',
ref = document.getElementsByTagName('script')[0];
if (document.getElementById(id)) {
return;
}
js = document.createElement('script');
js.id = id;
js.async = true;
js.src = "//connect.facebook.net/en_US/sdk.js";
ref.parentNode.insertBefore(js, ref);
}
}
AppComponent:
import { Component, OnInit, NgZone } from '@angular/core';
import { Observable } from "rxjs/Observable";
import { FacebookService } from "app/Services/facebook.service";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'app.component works!!!';
name = "";
isUser = false;
constructor(private _ngZone: NgZone, private _facebookService: FacebookService) {
}
ngOnInit() {
this._facebookService.loadAndInitFBSDK();
/* if (this.checkLoginState()) { // Error in :0:0 caused by: FB is not defined
this.setIsUser();
this.setName();
} */
}
login() {
var self = this;
FB.login(function (response) {
if (response.authResponse) {
FB.api('/me', function (response) {
self._ngZone.run(() => {
self.name = response.name;
self.isUser = true
});
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
});
}
logout() {
FB.logout(function (response) {
location.reload();
});
}
checkLoginState() {
let isLoggedIn;
FB.getLoginStatus(function (response) {
if (response.authResponse) {
isLoggedIn = true;
} else {
isLoggedIn = false;
}
});
return isLoggedIn;
}
setName() {
var self = this;
FB.api('/me', function (response) {
self._ngZone.run(() => {
self.name = response.name
});
});
}
setIsUser() {
var self = this;
FB.api('/me', function (response) {
self._ngZone.run(() => {
self.isUser = true
});
});
}
}
app.component.html
<h1>
{{title}}
</h1>
<div>
<div *ngIf="!isUser" id="Login">
<button (click)="login()">Log in with Facebook</button>
</div>
<div *ngIf="isUser" id="Logout">
<button (click)="logout()">Logout</button>
</div>
</div>
<div *ngIf="isUser">
<h2> Welcome {{name}} </h2>
</div>
<div *ngIf="!isUser">
<p> Login please! </p>
</div>
<router-outlet></router-outlet>
的AppModule:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
import { DashboardComponent } from './Components/dashboard/dashboard.component';
import { MainComponent } from './Components/main/main.component';
import { PageNotFoundComponentComponent } from './Components/page-not-found-component/page-not-found-component.component';
import { FacebookService } from "app/Services/facebook.service";
const appRoutes: Routes = [
{ path: 'dashboard', component: DashboardComponent, canActivate: [] },
{ path: '', component: MainComponent },
{ path: '**', component: PageNotFoundComponentComponent }
];
@NgModule({
declarations: [
AppComponent,
DashboardComponent,
MainComponent,
PageNotFoundComponentComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
RouterModule.forRoot(
appRoutes,
{ enableTracing: false } // <-- debugging purposes only
)
],
providers: [FacebookService],
bootstrap: [AppComponent]
})
export class AppModule { }
答案 0 :(得分:1)
将它们全局保存在localStorage中。
这是一个教程,展示了如何(不是Facebook,但原则仍然适用):http://jasonwatmore.com/post/2016/09/29/angular-2-user-registration-and-login-example-tutorial