4

How does this code change wrt to the new HttpClientModule, where mapping from response.json() is not required.

    //uses Http
    getLegalTerms(): Observable<legalterm[]> {
        return this._http.get(this._legalTermUrl)
        .map((response: Response) => <legalterm[]> response.json());
    }

i get nothing back if I do the following

    //uses HttpClientModule
    getLegalTerms(): Observable<legalterm[]> {
        return this._http.get<legalterm[]>(this._legalTermUrl)
    }

I am subscribing in the component class in the same way in either case

     ngOnInit() {
        this._legalTermService.getLegalTerms()
         .subscribe((legalTerms: LegalTerm[])  =>  {
         this.legalTerms = legalTerms;
      })
    }

I get data in the grid with Http but no data in grid with HttpClient

Thank you! Anand

Anand
  • 1,387
  • 2
  • 26
  • 48
  • The code looks correct. What do you mean you get nothing back? The angular http observable does not run unless you subscribe to it. – LLai Nov 07 '17 at 16:04
  • @LLai I am subscribing to this method in the component class – Anand Nov 07 '17 at 16:33
  • so the http request is firing and you do receive legalTerms? – LLai Nov 07 '17 at 16:39
  • @LLai - yes, answered below – Anand Nov 07 '17 at 17:05
  • What you have is correct. With `this._http.get` you are saying the http response will return type `legalterm[]` which matches with your method output type `Observable`. This is the correct way to strongly type your getLegalTerms method – LLai Nov 08 '17 at 07:00
  • 1
    Yes, it does work. not sure why this would not work before... – Anand Nov 08 '17 at 16:49

1 Answers1

2

It should be,

 getLegalTerms(): Observable<legalterm[]> {
        return this._http.get(this._legalTermUrl)
        //.map((response: Response) => <legalterm[]> response);
       .map((response: Response) => <any> response);
 }
Anand
  • 1,387
  • 2
  • 26
  • 48
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
  • I gave the upvote as it was a correct answer. but somebody gave the downvote for no reason (might be the question owner I guess). these people don't have the courage to appreciate those who help – VithuBati Nov 07 '17 at 16:12
  • @Sajeetharan - thanks but the problem is type Reponse cannot be converted to LegalTerm[] – Anand Nov 07 '17 at 16:30
  • try changing as any and then convert inside the component – Sajeetharan Nov 07 '17 at 16:31
  • This *IS* correct for the OLD Http not the NEW HttpClient. If you are using the new HttpClient you should *NOT* need to map. The OP's syntax was correct and this is NOT. – DeborahK Nov 07 '17 at 22:35