简体   繁体   中英

@Input as Observable<string> in Angular 2/4/5

This sample intention was to check ChangeDetection.

When i am trying to pass data from homecomponent to childcomponent using @input property which is an Observable gives the below Error :

Unhandled Promise rejection: Cannot read property 'subscribe' of undefined ; Zone: <root> ; Task: Promise.then ; Value: TypeError: Cannot read property 'subscribe' of undefined
at changeDetectionChildComponent.ngOnInit (child.component.ts:20)
at checkAndUpdateDirectiveInline (provider.ts:275)
at checkAndUpdateNodeInline (view.ts:456)
at checkAndUpdateNode (view.ts:417)
at debugCheckAndUpdateNode (services.ts:235)
at debugCheckDirectivesFn (services.ts:294)
at Object.eval [as updateDirectives] (parent.html:4)
at Object.debugUpdateDirectives [as updateDirectives] (services.ts:273)
at checkAndUpdateView (view.ts:345)
at callViewAction (view.ts:700) TypeError: Cannot read property 'subscribe' of undefined

Below is the sample Project i have created

home.component.ts

    import { Component } from "@angular/core";
    import { Observable } from "rxjs/Observable";

    @Component({
        selector:'changeDetectorHome',
        templateUrl:'ChangeDetection/Views/parent.html'
      })
      export class changeDetectionHomeComponent {
      myData:{firstname:string,lastname:string}
      message:string;
        constructor(){

            this.myData={
                firstname: 'Debasish',
                lastname:'K'
            }
        }


        changeName() {
          this.myData.firstname = 'Brad';
          this.myData.lastname='pitt';
          this.message="somedata";
              }
      }

home.html -view of home component

  <h1>{{myData.firstname}} {{myData.lastname}}</h1> <button (click)="changeName()">Change name</button> <child [passObjectTochild]="myData" [passStringTochild]="message"></child> 

child.component.ts

        import { Component, Input, ChangeDetectionStrategy, OnInit, ChangeDetectorRef } from "@angular/core";
        import { Observable } from "rxjs/Observable";


        @Component({
            selector:'child',
            templateUrl:'ChangeDetection/Views/child.html',
            changeDetection: ChangeDetectionStrategy.OnPush
          })
         export  class changeDetectionChildComponent implements OnInit{

           @Input('passObjectTochild') data:{firstname:string,lastname:string};
           @Input('passStringTochild') data1:Observable<string>;
           counter:number=0;
            constructor(private cd: ChangeDetectorRef){

            }

            ngOnInit(){
              this.data1.subscribe(
              ()=>{
                this.counter ++;

            })}


          }

changeDetection.Module.ts

    import { NgModule } from "@angular/core";
    import {BrowserModule } from '@angular/platform-browser'
    import { changeDetectionHomeComponent } from "./home.component";
    import { changeDetectionChildComponent } from "./child.component";

    @NgModule({
        imports:[BrowserModule],
        declarations:[changeDetectionHomeComponent,changeDetectionChildComponent],
        bootstrap:[changeDetectionHomeComponent]
    })
    export class changeDetectionModule{ }

main.ts

import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'
import { changeDetectionModule } from './changedetection.module';

platformBrowserDynamic().bootstrapModule(changeDetectionModule);

you need to initialize your observable in your child component and put a default value , that is causing the error, try this solution

 @Input('passStringTochild') data1:Observable<string>= Observable.of(null); 

in that way your observable always is going to be initialized, when you pass the input from the parent will be overwritten

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM