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

mes*_*lds 4 typescript ionic2 angular

错误

TypeError:无法读取null的属性"next"

模板调用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>
  `
})
Run Code Online (Sandbox Code Playgroud)

有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);
}
Run Code Online (Sandbox Code Playgroud)

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, [])
Run Code Online (Sandbox Code Playgroud)

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

Ionic2,将NavController注入可注射服务

Can*_*yen 7

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

无论如何,你正在实现什么dismiss,dismissObserver是一个概念Subject.只需替换您的NavService构造函数,然后goHome:

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

public goHome():void {
  this.dismiss.next(true);
}
Run Code Online (Sandbox Code Playgroud)

你很好:如果你的订阅在它之后,你可能会错过价值,但不会抛出任何错误.尝试更换SubjectBehaviorSubject缓存一个值发射后前来订阅.

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