0

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
    }
}
Giannis
  • 1,790
  • 1
  • 11
  • 29
AshH
  • 39
  • 7

2 Answers2

0

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);
   });
}
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
0

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.

noririco
  • 765
  • 6
  • 15