获取对象角度CLI的数组

时间:2019-04-28 15:09:22

标签: angular http get

嗨,我正在尝试从angular的get请求中获取数据。我有一班公寓,看起来像这样:

export class Apartment {

  id: number;
  address: string;

  constructor(id: number, name: string) {

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

服务

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

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

 constructor(private httpClient: httpClient) {}

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

一个组件

 export class SettingsComponent implements OnInit {

 apartments: Apartment[] = [];

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

我有一个可以正常工作的rest api和一个读取的json文件,如下所示:

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

我如何读取数据并将其投射到Apartment数组中?

3 个答案:

答案 0 :(得分:1)

如果您没有任何特定于类的方法,那么我自己不在这里使用一个类,而只是一个接口。但是,如果您确实想拥有一个类并为该类创建数据实例,则需要映射数据,这里假设您已获得一个数组。还要告诉angular您在请求中得到了什么:

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

然后在您的组件中:

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

但是正如我提到的,如果类中没有方法,我将使用接口:

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

和获取请求,简单地:

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

并订阅上述组件。

答案 1 :(得分:0)

在您的订阅中,您只需要这样声明(data:any)

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

答案 2 :(得分:0)

您的API是否返回公寓列表?如果是,您可以采用这种方式-

export class SettingsComponent implements OnInit {

  apartments: Apartment[] = [];

  constructor(private apiService: Service) {}
}

ngOnInit(){
  this.fetchApartments();
}

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

或者

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