TypeError:无法读取属性' next'在Angular2 Observable中的null

时间:2016-07-12 14:05:28

标签: typescript angular ionic2

错误

  

TypeError:无法读取属性' next'为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 with subscription

@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, [])

顺便说一下,我正在使用这个&#34;教程&#34;:

Ionic2, inject NavController to Injectable Service

1 个答案:

答案 0 :(得分:6)

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

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

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

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

并且你很好:如果您的订阅在它之后,您可能会错过价值,但不会引发任何错误。尝试将Subject替换为BehaviorSubject,以便为发布后的订阅缓存一个值。

编辑:我忘记提到你需要import { Subject } from 'rxjs/Subject';