简体   繁体   中英

Initialise observable values to any object or array in Angular

Making a rest get call to firebase, below is database structure

angularapp-9421c
 posts
  -NH5y6B3ohYRettJXM42
     name: "John"
  -NH5zWuR_ZJxOBQUkMyc
     name: "Mary"

Get call

response : any;

 getHttpData(){
    this.http.get(this.url).subscribe(
      data => this.response = data
    );
  }

I got the response successfully, need to initialise these values in any string/array object. I have tried type casting the response, facing issue with key (NH5y6B3ohYRettJXM42, NH5zWuR_ZJxOBQUkMyc). What should be the interface structure to typecast the response.

Suggestion

For a data structure like below

-NH5y6B3ohYRettJXM42
     name: "John"
  -NH5zWuR_ZJxOBQUkMyc
     name: "Mary"

You can create an interface for the response like below

// Define an interface for your response object

interface PostResponseDocument {
  name: string;
}

interface PostResponse {
  [key: string]: PostResponseDocument;
}


// Declare your response variable to be of PostResponse

response: PostResponse;


// Apply interface to the get method

getHttpData(){
  this.http.get<PostResponse>(this.url).subscribe(data => 
     this.response = data;
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM