更新时间:2023-12-03 17:14:58
查看活动文档
它们允许您从任何页面发布"操作,并在另一个页面中订阅它以检索值.你的场景看起来有点像这样.
They allow you to 'publish' an action from any page, and subscribe to it in another page to retrieve the value. Your scenario would look a bit like this.
导入(在 Facebooklogin.component
和 app.component
上)
Import (both on Facebooklogin.component
and app.component
)
import { Events } from 'ionic-angular';
和你的构造函数 constructor(public events: Events)
然后,每当您更改 userName
(例如在 facebook 登录的处理程序中)时,都会像这样发布值.
Then, whenever you change your userName
(f.e. in the handler of the facebook login) publish the value like this.
fbLogin() {
Facebook.login(["public_profile", "email"])
.then((resp: FacebookLoginResponse) => {
if (resp.status === "connected") {
Facebook.api("/me", ["public_profile", "email"])
.then(res => {
this.userName = res.name
// publish the username change to the events
this.events.publish('username:changed', this.userName);
this.login({name: this.userName})
})
//...
);
}
并订阅在您的 app.component
中进行的任何发布
And subscribe to any publishes being made in your app.component
userName: string;
constructor(events: Events) {
this.userName = "not logged in";
events.subscribe('username:changed', username => {
if(username !== undefined && username !== ""){
this.userName = username;
}
}) //...
}
EventEmitter
EventEmitter
import { EventEmitter } from '@angular/core';
public userChanged = new EventEmitter();
fbLogin() {
Facebook.login(["public_profile", "email"])
.then((resp: FacebookLoginResponse) => {
if (resp.status === "connected") {
Facebook.api("/me", ["public_profile", "email"])
.then(res => {
this.userName = res.name
// publish the username change to the events
this.userChanged.emit(this.userName);
this.login({name: this.userName})
})
...
);
}
App.component
App.component
import { FacebookLogin } from '../pages/facebook/facebook.component';
public userName;
constructor(fb: FacebookLogin){
this.userName = "";
//subscribe to the page's EventEmitter
this.fb.userChanged.subscribe(username => {
this.userName = username;
});
}
或使用 EventEmitter
作为 Output
,如本 S.O. 中所述.回答:EventEmitter 的正确用法是什么?
OR use the EventEmitter
as an Output
as described in this S.O. answer: What is the proper use of an EventEmitter?