Tuesday, February 11, 2020

How to solve "ERROR TypeError: Cannot read property 'subscribe' of undefined" in angular development?

after i completed my sample angular application, i ran it the result did show in the page.

however there was an error message in the console in the development tool.

"ERROR TypeError: Cannot read property 'subscribe' of undefined" 

core.js:5828 ERROR TypeError: Cannot read property 'subscribe' of undefined
    at AppComponent.ngOnInit (app.component.ts:24)
    at callHook (core.js:3892)
    at callHooks (core.js:3856)
    at executeInitAndCheckHooks (core.js:3797)
    at refreshView (core.js:11706)
    at renderComponentOrTemplate (core.js:11814)
    at tickRootContext (core.js:13290)
    at detectChangesInRootView (core.js:13324)
    at RootViewRef.detectChanges (core.js:15004)

    at ApplicationRef.tick (core.js:42192)


THE ROOT CAUSE OF THIS ERROR IS StocksService had been subscribed twice, one in the AppComponent, another one is in the DashBoard Component. after i comment out the code in the AppComponent. the error is gone. it is also a bad idea to call the service the AppComponent. since i had the routing enable.


export class AppComponent {
  stocksArray<StockInterface>;
  symbolsArray<string>;
  constructor(private serviceStocksService){
    //  this.service.load(['APPL']).subscribe(stocks=>{
    //    this.stocks=stocks;
    //  }
      // );
   }

   ngOnInit(){
     this.service.load(this.symbols).subscribe(stocks=>{
       this.stocks=stocks;
     });
   }
}



export class DashboardComponent implements OnInit {
  stocksArray<StockInterface>;
  symbolsArray<string>;
  constructor(private serviceStocksService) {
      this.symbols=service.get();
   }
  ngOnInit(): void {
    this.service.load(this.symbols).subscribe(
      stocks=>this.stocks=stocks);
  }
}

No comments:

Post a Comment