ANGULAR 2 - 组件共享数据服务

时间:2016-12-01 00:12:35

标签: angular angular2-template angular2-services

这真的让我头晕目眩。

我有一个很好的小应用程序,使用Firebase和Angular 2进行社交登录设置。

一切都应该是实时的。基本上,当用户通过Facebook登录时,我希望将他们的个人信息传递给服务并存储为Observable并立即显示在订阅该服务的任何组件中,然后我希望能够从组件中访问此Observable并没有直接相互关联,甚至可能完全不在层次结构中..因此我不能使用@Input或EventEmitter等。

我尝试了很多不同的东西,但最重要的是,这是我目前所拥有的,一个将用户数据传递给服务的登录组件,然后是一个应该能够实时访问这些数据的随机组件一旦它到达服务。

*我的登录组件*

import { Component, OnInit } from '@angular/core';
import { AngularFire, AuthProviders, AuthMethods, FirebaseListObservable } from 'angularfire2';
import { Router } from '@angular/router';
import { GlobaluserService } from '../globaluser.service';
import { Subject }    from 'rxjs/Subject';


@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
})
export class LoginComponent  {

  email: string;
  password: string;
  userData = {};
  _api;

  constructor( public af: AngularFire,  private router: Router, private api: GlobaluserService ) {
    this._api = this.api;
  }

  loginFacebook() {
    this.af.auth.login({
      provider: AuthProviders.Facebook,
      method: AuthMethods.Popup,
    }).then( ( facebookUser ) => {

        this.userData = {
          uID: facebookUser.auth.uid,
          profilePic: facebookUser.auth.photoURL,
          username: facebookUser.auth.displayName,
          email: facebookUser.auth.email,
          platform: 'facebook'
        }

        this._socialLoginProcess( this.userData );  // this method is described below

    }).catch( (error) => {
      console.log("Facebook failure: " + JSON.stringify(error));
    });
  }

  // passes the user data to the shared service and outputs the data in the console
  _socialLoginProcess( userData ) {
    this._api.saveData(userData); 
    console.log("Login Success: " + JSON.stringify( this.userData )); 
  }


}

*共享服务*

import { Component, Injectable,Input,Output,EventEmitter } from '@angular/core';
import { Subject }    from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import 'rxjs/add/operator/map';


// Name Service
export interface usersData {
    uID: string,
    profilePic: string,
    username: string,
    email: string,
    platform: string
}


@Injectable()
export class GlobaluserService {

  sharingData: Observable<usersData[]>

  private _sharingData: BehaviorSubject<usersData[]>;

  private dataStore: {
    sharingData: usersData[]
  };


  constructor() {
    this.dataStore = { sharingData: [] };
    this._sharingData = <BehaviorSubject<usersData[]>>new BehaviorSubject([]);
  }

  saveData( userData ) {
    this.sharingData = userData; 
  }

  getData()  {
    console.log('get data function called' +  JSON.stringify( this.sharingData ) );
    return this._sharingData.asObservable();
  }


}

*随机组件我希望能够从此服务获取用户数据*

import { Component, OnInit, Input } from '@angular/core';
import { AngularFire, AuthProviders, FirebaseListObservable } from 'angularfire2';
import { Router } from '@angular/router';
import { GlobaluserService } from '../globaluser.service';

@Component({
selector: 'app-navigation',
templateUrl: './navigation.component.html',
styleUrls: ['./navigation.component.css']
})

export class NavigationComponent implements OnInit  {

  isAuth = false;
  user   = {};

  subscription   : any;
  userKonte      : any;
  _userAPIservice: any;

  constructor( private router: Router, private api: GlobaluserService ) {

      this.subscription    = this.api.getData().subscribe( _sharingData => {
          this.userKonte = _sharingData;
          console.log( JSON.stringify( this.userKonte )  );
      });

  }

    ngOnInit(){
      console.log( JSON.stringify( this.userKonte )  );
    }





}

1 个答案:

答案 0 :(得分:0)

而不是

saveData( userData ) {
  this.sharingData = userData; 
}

如果要发出新值,则需要next上的BehaviorSubject

saveData( userData ) {
  this._sharingData.next(userData); 
}

因为getData正在从主题中获得观察结果,所以当next被调用时,观察者的订阅者将在主题上获得新的排放