0

I realize that the new updates don't require conversion of a response to JSON.

The tutorial I am following puts this into the api.service.ts

export class ApiService {

  constructor(private http: HttpClient){}

  messages = []
  getMessage(){
    this.http.get('http://localhost:3000/newroute').subscribe(res =>{
      this.messages = res.json()
    })
  }

}

However, with the new update, "res.json()" does not work. I get the following error: Property 'json' does not exist on type 'Object'.

How can I solve this?

Here is the data I'm trying to loop through:

var posts = [
{message:'Hello World'},
{greeting:'Whats going on'}
]
amihac
  • 1
  • 1

3 Answers3

0

Simply do:

getMessage(){
  this.http.get('http://localhost:3000/newroute').subscribe(res =>{
  this.messages = res;
  })
}
Shashank Vivek
  • 16,888
  • 8
  • 62
  • 104
0

Angular allows you to do type checking on the response. You don't have to manually parse JSON.

Here is a code snippet from your example (I recommend using types):

messages: Message[] = []
getMessage() {
  this.http.get<Message[]>('http://localhost:3000/newroute').subscribe((res: Message[]) => {
    this.messages = res;
  });
}

(Update)

Based on your provided data, an interface for Message could look like this:

export interface Message {
  [s: string]: string;
}

However, if "Messages" can only have specific keys like "message" and "greeting", then you can add any of those as optional properties as well.

export interface Message {
  message?: string;
  greeting?: string;
}
  • I get this error for 'this.messages': The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead? – amihac Feb 21 '19 at 04:14
  • It depends on what type of data you are returning. If you update your question with a sample of return data, I can update the answer to help you more accurately –  Feb 21 '19 at 04:16
  • Added to the question! var posts = [ {message:'Hello World'}, {greeting:'Whats going on'} ] – amihac Feb 21 '19 at 04:23
  • Actually, did you mean the error is on this line `messages: Message[] = []` or this line `this.messages = res;`? –  Feb 21 '19 at 04:27
  • @amihac I updated the answer to also include the return type being passed in as a generic on the `http.get` method. Your issue may be a combination of this and/or res not having a type specified `.subscribe((res: Message[]) =>` instead of `.subscribe(res =>`. –  Feb 21 '19 at 04:36
  • THANK YOU! Including the type Message[] worked! Thank you! @OneLunch Man – amihac Feb 21 '19 at 05:42
  • You're welcome! Please don't forget to mark as answer if this solved your problem- –  Feb 21 '19 at 13:53
-1

HttpClient gives you json object only, so no need to do .json() again.So do the following code it works for you

getMessage(){
  this.http.get('http://localhost:3000/newroute').subscribe(res =>{
  let messages: any = res;
  this.messages = messages;
  })
}