离子 4 可观察量

Ionic 4 Observables

我一直在尝试在 Ionic 4 升级项目中实现 rxjs Observable 模式但没有成功,我想知道如何成功实现 Observable 以便在屏幕上显示预期结果。

This is the old way of doing things and somewhere 'user:loggedIn' is used to display x results on-screen.

 events.subscribe('user:loggedIn', (userEventData) => {
   this.getUserInfo(userEventData);
   this.registerPushNotifications();
   this.registerPushNotificationHandlers();
 });

实现和测试了两种方法,但没有显示结果。

方法一:

    let userLoggedIn = new Observable((observer) => {
      // const {next, error} = observer;

      observer.next({'user:loggedIn':observer});
      observer.complete();
    });

    userLoggedIn.subscribe((userEventData) => {
      console.log(userEventData)
      this.getUserInfo(userEventData);
      this.registerPushNotifications();
      this.registerPushNotificationHandlers();
    });

方法二:

    var observer: Observable<any> = of();
    observer.subscribe(userEventData => {
      this.getUserInfo(userEventData);
      this.registerPushNotifications();
      this.registerPushNotificationHandlers();
    });

Is there a way to have the same functionality as the old Ionic events functionality in Ionic 4 using Observable or Subject implementations?

这是一种可能适合您的方法。在您的身份验证服务中,您可以创建一个私有的 BehaviorSubject 属性 来存储私有登录的最后一个值 属性。然后你可以创建一个 public observable 以 BehaviorSubject 作为它的来源。最后,您可以在 page/component 中订阅该服务的 public observable,当登录状态 属性 发生更改时,它可以获取和设置您需要的任何内容。这是它如何工作的一个简单示例:

loginService.ts

export class LoginService {
  private login: boolean = false;
  private loginSubject$ = new BehaviorSubject<boolean>(this.login);
  loginChanged$ = this.loginSubject$.asObservable();

  constructor() { }

  updateLogin(){
    this.login = !this.login;
    this.loginSubject$.next(this.login);
  }
}

home.page.ts

export class HomePage implements OnInit, OnDestroy {

  timesClicked:number=0;
  loginButtonText:string;

  loginChangedSubscription: Subscription

  constructor(private loginService: LoginService) {}

  ngOnInit() {
    this.loginChangedSubscription = this.loginService.loginChanged$.subscribe((loginValue)=>{
      this.timesClicked += 1;
      this.loginButtonText =  (loginValue ? "Log Me Out" : "Log Me In");
    })
  }

  ngOnDestroy(): void {
    if (this.loginChangedSubscription) {
      this.loginChangedSubscription.unsubscribe();
    }
  }

  updateLogin():void{
    this.loginService.updateLogin();
  }
}

只是为了展示它的工作.... home.page.html

<ion-content>
  <ion-item>
    <ion-label>
      {{timesClicked}}
    </ion-label>
  </ion-item>
  <ion-button color="primary" (click)="updateLogin()">{{loginButtonText}}</ion-button>
</ion-content>

希望这对您有所帮助。