ANGULAR 2-组件共享数据服务 [英] ANGULAR 2 - Component Shared Data Service

查看:87
本文介绍了ANGULAR 2-组件共享数据服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这真让我头疼.

我有一个不错的小应用程序,具有使用Firebase和Angular 2进行社交登录的设置.

I have a nice little app with social login setup using Firebase and Angular 2.

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

Everything should be realtime. Basically when a user logs in via Facebook I want their personal info to be passed to a service and stored as an Observable and display instantly in any component that subscribes to the service, I then want to be able to access this Observable from within Components that are not directly linked to each other and may even be totally out of the hierarchy.. hence why I cant use @Input or an EventEmitter etc..

我已经尝试了很多不同的方法,但最简单的是,这是我目前拥有的东西,一个将用户数据传递到服务的登录组件,然后是一个应该能够实时访问此数据的随机组件.一旦它到达服务.

I have tried a lot of different things but at its most stripped back this is what i currently have, a login component that passes the users data to the service and then a random component that should be able to access this data in realtime as soon as it hits the service.

*我的登录组件*

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 )  );
    }





}

推荐答案

代替

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

当要发出新值时,需要在BehaviorSubject

when you want to emit a new value, you need to next on the BehaviorSubject

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

由于getData正在从主体获取可观测对象,因此调用next时,可观测对象的订户将获得关于主体的新发射

Because getData is getting the observable from the subject, the subscribers to the observable will get the new emissions on the subject when next is called

这篇关于ANGULAR 2-组件共享数据服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆