get undefined for data assigned in service in angular 6

221 Views Asked by At

I don't want to call the service in the .ts file. It will cause a lot of time. So I just want to assigned this as a global value that I can use, but I keep get undefined

Here is my service file

@Injectable({
  providedIn: 'root'
})
export class DeService {

  data:any;

  constructor(private http: HttpClient){}


  getData(id:any):Observable<any>{
    this.http.get(Url.getDetails+"id="+id).pipe(first()).subscribe(res=>{
        this.data = res;
        console.log(this.data)   //Here I got the data
    }
    return this.http.get(Url.getDetails+"id="+id)
    }
}

the ts file

export class text implements OnInit{

    constructor(public de:DeService){}

    ngOnInIt(){
        console.log(this.de.data);   //here it returns undefind
    }
}
2

There are 2 best solutions below

0
On

You cannot access the observable like that, you need to call the method and subscribe to the method as follows,

getData(id:any):Observable<any>{
  return this.http.get(Url.getDetails+"id="+id);
}

and in component,

ngOnInIt(){
   this.de.getData(id).subscribe((data)=>{
     console.log(data);
   });
}
0
On

Since you are using Observable, and Observable works with async data, your data:any; is not initialized therefore it logs undefined.

This is happening

export class text implements OnInit{

    constructor(public de:DeService){}

    ngOnInIt(){
        console.log(this.de.data);   //here it returns undefind
    }
}

Before this:

  getData(id:any):Observable<any>{
    this.http.get(Url.getDetails+"id="+id).pipe(first()).subscribe(res=>{
        this.data = res;
        console.log(this.data)   //Here I got the data
    }
    return this.http.get(Url.getDetails+"id="+id)
  }

To fix this you must set the data:any to some value or use @Sajeetharan solution ofcourse.