错误FB未通过Angular2(CLI)定义Facebook登录



我想将Facebook身份验证用作角度服务。使用此代码,我可以登录/注销生命周期) - 我尝试在ngoninit中 chemloginstate()知道是否仍登录用户,如果他是他,我会查询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 { }

在您的localstorage中保存它们。

这是一个教程,它显示了如何(不适用Facebook,但原则仍然适用):http://jasonwatmore.com/post/2016/09/29/angular-29/angular-2---------------------- registration-and-registration-and-login-example-tutorial

最新更新