[英]ANGULAR 2 - Component Shared Data Service
this has really been wreaking my head. 这真的让我头疼。
I have a nice little app with social login setup using Firebase and Angular 2. 我有一个很好的小应用程序,使用Firebase和Angular 2进行社交登录设置。
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..
基本上,当用户通过Facebook登录时,我希望将他们的个人信息传递给服务并存储为Observable并立即显示在订阅该服务的任何组件中,然后我希望能够从组件中访问此Observable没有直接相互关联,甚至可能完全不在层次结构中..因此我不能使用@Input或EventEmitter等。
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. 我已经尝试了很多不同的东西,但最重要的是,这是我目前拥有的,一个将用户数据传递给服务的登录组件,然后是一个应该能够实时访问这些数据的随机组件它击中了服务。
* my login component * *我的登录组件*
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 ));
}
}
* Shared Service * *共享服务*
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();
}
}
* Random Component I wish to be able to get the users data from this service * *随机组件我希望能够从此服务获取用户数据*
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 ) );
}
}
Instead of 代替
saveData( userData ) {
this.sharingData = userData;
}
when you want to emit a new value, you need to next
on the BehaviorSubject
当你想要发出一个新值时,你需要在
BehaviorSubject
上next
saveData( userData ) {
this._sharingData.next(userData);
}
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 因为
getData
正在从主题中获得可观察性,所以当下next
被调用时,observable的订阅者将获得关于该主题的新发射
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.