【问题标题】:TypeError: Cannot read property 'next' of null in Angular2 ObservableTypeError:无法读取 Angular2 Observable 中 null 的属性“下一个”
【发布时间】:2016-11-14 19:58:17
【问题描述】:

错误

TypeError: 无法读取 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>
  `
})

可观察服务

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

【问题讨论】:

  • 好的,让我提供代码

标签: typescript angular ionic2


【解决方案1】:

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';

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-29
    • 2022-01-12
    • 2021-12-04
    • 2021-12-17
    • 2022-01-09
    • 1970-01-01
    相关资源
    最近更新 更多