Angular http.get - 转换结果

Angular http.get - Transforming result

Angular 8

我有一个 http.get :

this.http.get("https://BahaiPrayers.net/api/prayer/Languages")
  .subscribe(data => {
       //return a different object
  });

来自服务器的 json 如下所示:

{
 Id: 1,
 Name: "English",
},....

我需要 http.get 将数据转换成我的这个 class 的打字稿数组:

 export class Language {
      languageId: number;
      englishName: string;
  }

有没有办法让 http.Get 转换为我的对象?

您可以在服务中尝试这样的事情:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

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

    constructor(private httpClient: HttpClient) { }

    getLanguages(): Observable<Language[]> {
        return this.httpClient.get<any[]>('https://BahaiPrayers.net/api/prayer/Languages')
        .pipe(
            //** This is where the tranformation happens
            map(lanuages => lanuages.map(language => (
               { languageId: language.Id, englishName: language.Name })))
            //** change language.Name to language.English 
            //** if you need the English name of the language 
        );
    }
}

export class Language {
    languageId: number;
    englishName: string;
}

然后从一个组件调用getLanguage()

import { Component, OnInit } from '@angular/core';
import { LanguageService, Language } from '../services/language.service';

@Component({
    selector: 'app-language',
    templateUrl: './language.component.html',
    styleUrls: ['./language.component.css']
})
export class LanguageComponent implements OnInit {
    languages: Language[];

    constructor(private languageService: LanguageService) { }

    ngOnInit() {
        this.languageService.getLanguages().subscribe(
            languages => this.languages = languages);
    }
}

自最近的 Angular 版本以来,如果您的对象与 JSON 共享相同的属性,则不再需要映射结果(它将自动完成):

export class Language {
  Id: number;
  Name: string;
}
...

然后在服务中:

getLanguages(): Observable<Language[]> {
    return this.httpClient.get<Language[]>('https://BahaiPrayers.net/api/prayer/Languages');
}