-2
  updload(name,age,address)
  {
    debugger;
    this.data=this.service.tryinsert(name,age,address);
    this.data.subscribe(
     (respose:any)=>{
        console.log(respose);
      }
    )
  }
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

I have imported the above two files but when I pass the data for name,age, address from the browser, it says

ERROR TypeError: Cannot read property 'subscribe' of undefined

halfer
  • 19,824
  • 17
  • 99
  • 186
Vishwas C
  • 1
  • 3
  • What does `this.service.tryinsert` return? It doesn't appear to return anything. –  Jan 20 '20 at 18:42

1 Answers1

1

The question says

ERROR TypeError: Cannot read property 'subscribe' of undefined

because by the time this.data.subscribe() is called the variable this.data has not yet been assigned any value.

Service functions are almost always observables in angular and therefore asynchronous. This means that the response of the server will be dependent on several factors and not instantaneous.

To correct your code you would use it like below:

updload(name,age,address)
  {
    debugger;
    this.service.tryinsert(name,age,address)
        .subscribe(responseData => {
            console.log(responseData);
            // use the code below if responseData is not of type string
            // console.log(JSON.stringify(responseData));
    });

   }
halfer
  • 19,824
  • 17
  • 99
  • 186
Ian Preglo
  • 421
  • 2
  • 10
  • Thanks for the quick response Preglo, but it gives an error as "Property 'subscribe' does not exist on type 'void'.", what should i do now? – Vishwas C Jan 20 '20 at 12:04
  • I can't really tell you what you will do with your code but that should be obvious by now :D your service function needs to be of Observable type. You can study this one in the Angular documentations as well. – Ian Preglo Jan 20 '20 at 12:25
  • yes Preglo, the service method was not of observable type, it worked for me later doing the service as of observable type – Vishwas C Feb 14 '20 at 12:48