2

Hi I'm trying to fetch data from a get request in angular. I have a class Apartment that looks like this:

export class Apartment {

  id: number;
  address: string;

  constructor(id: number, name: string) {

      this.id = id;
      this.name = name;
 }
 }

A service

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

 baseURL = 'http://localhost:3000';

 constructor(private httpClient: httpClient) {}

 getApartments() {
     return this.httpClient.get(this.baseURL + '/apartments');
 }
 }

A component

 export class SettingsComponent implements OnInit {

 apartments: Apartment[] = [];

 constructor(private apiService: Service) {
   // todo: fetch data here...
}}

I have a rest api that works and a json file to read that look like this:

 {
   "id" : 0,
   "address: "not assinged yet"
 }

How can I read and cast the data to an array of Apartment?

3 Answers 3

1

If you do not have any class specific methods, I would not use a class here myself, just an interface. But if you do want to have a class and create instances of your data to that class, you need to map your data, here assumingly you get an array. Also tell angular what you are getting in your request:

 getApartments() {
   return this.httpClient.get<Apartment[]>(this.baseURL + '/apartments').pipe(
     map((arr) => arr.map(x => new Apartment(x.id, x.address)))
   )
 }

Then in your component:

ngOnInit() {
  this.apiService.getApartments()
    .subscribe((data: Apartment[]) => this.apartments = data);
}

But as I mention, I would use an interface if there are no methods in the class:

export interface Apartment {
  id: number;
  address: string;
}

and the get request, simply:

 getApartments() {
   return this.httpClient.get<Apartment[]>(this.baseURL + '/apartments')
 }

and subscribe in the component mentioned above.

Sign up to request clarification or add additional context in comments.

3 Comments

if I use an interface and the relative getApartments method I still need to subscribe or getApartments call is enough?
With http-requests we are dealing with cold observables, you always need to subscribe, either with subscribe or using async pipe in template :)
If not needing to work with the data received in your TS file, it is very convenient to use the async pipe: angular.io/api/common/AsyncPipe But if you need to manipulate the data somehow in the TS file, I would suggest to use subscribe.
0

In your subscribe you only need declare (data:any) like this

constructor(private apiService: Service) {
    this.apiService.getApartments().subscribe((data:any)=>{
        this.apartments = data;
    });
}

3 Comments

Do not use any. That defeats the purpose of TYPEscript. Always type your data, even if only for your own sake. Assumingly you want to make your life easier with debugging ;)
in this case he defined type for apartments, if you dont use any, it show error cant not cast
Well, then use the type defined, not any.
0

Does your API return a list of apartments? If yes you can approach like this-

export class SettingsComponent implements OnInit {

  apartments: Apartment[] = [];

  constructor(private apiService: Service) {}
}

ngOnInit(){
  this.fetchApartments();
}

fetchApartments(){
  this.apiService.getApartments().subscribe(
    response => {
      this.apartments = response;
    }
  );
}

Or,

constructor(private apiService: Service) {
  this.apiService.getApartments().subscribe(
    response => {
      this.apartments = response;
    }
  );
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.