gpt4 book ai didi

typescript - 类型错误 : Cannot read property 'next' of null in Angular2 Observable

转载 作者:太空狗 更新时间:2023-10-29 17:47:01 25 4
gpt4 key购买 nike

错误

TypeError: Cannot read property 'next' of null

模板调用Observer.next(问题)

import { NavService } from '../../providers/services/nav-service/nav-service';

@Component({
selector: 'ion-header',
providers: [NavService],
template: `
<ion-navbar>
<ion-title>{{navService.getCurrentName()}}</ion-title>
<ion-buttons start>
<button (click)="navService.goHome()">
<span primary showWhen="ios">Cancel</span>
<ion-icon name="md-close" showWhen="android,windows"></ion-icon>
</button>
</ion-buttons>
</ion-navbar>
`
})

Observable 服务

import { Platform } from 'ionic-angular';
import { Observable } from 'rxjs/Observable';
import { Injectable, ViewChild } from '@angular/core'

@Injectable()

export class NavService {
private dismissObserver: any
public dismiss: any

constructor (
private authService: AuthService,
private platform: Platform
) {
this.dismissObserver = null;
this.dismiss = Observable.create(observer => {
this.dismissObserver = observer;
});
}

public goHome():void {
this.dismissObserver.next(true);
}

带订阅的 app.ts

@Component({
providers: [NavService]
})

export class MyApp {

@ViewChild(Nav) navController: Nav
constructor(
public navService: NavService

) {
this.initializeApp()
}

initializeApp() {

this.platform.ready().then(() => {

StatusBar.styleDefault()
this.setRoot()
this.navController.setRoot(HomePage);

this.navService.dismiss.subscribe((event) => {
console.log ("event", event);
this.navController.setRoot(HomePage)
})
})
}

ionicBootstrap(MyApp, [])

顺便说一句,我正在使用这个“教程”:

Ionic2, inject NavController to Injectable Service

最佳答案

Observable.create 中分配 dismissObserver 的代码在订阅 dismiss 时调用。因此,如果您在该订阅之前调用 goHome,则 dismissObserver 到那时为 null,您会收到错误

无论如何,您使用dismissdismissObserver 实现的是Subject 的概念。只需将 NavService 构造函数和 goHome 替换为:

constructor (
private authService: AuthService,
private platform: Platform
) {
this.dismiss = new Subject();
}

public goHome():void {
this.dismiss.next(true);
}

你没问题:如果你的订阅在它之后,你可能会错过值,但不会抛出错误。尝试用 BehaviorSubject 替换 Subject 来为发射后的订阅缓存一个值。

编辑:我忘了说你需要 import { Subject } from 'rxjs/Subject';

关于typescript - 类型错误 : Cannot read property 'next' of null in Angular2 Observable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38331194/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com