Error FB is not defined Facebook login with Angular2 (CLI)

Viewed 1262

I want to use Facebook authentication as an Angular service. With this code I'm able to login/logout but when I login and refresh the page the variables name and isUser are also refreshed/reinitialized (as I understand due to Angular Life Cycle) - I try to checkLoginState() in ngOnInit to know if the user is still logged in and if he is I will query FB API and will reinitialize the values of the variables again. But the code fails because in ngOnInit FB is not defined yet. So what can be done to maintain the variable values unchanged after page refresh? Or should I save them globally or in cache? Thanks!

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 { }
1 Answers
Related