Angular-HttpClient:将对象映射到数组属性

时间:2018-07-06 06:48:04

标签: angular rxjs angular6 angular-httpclient rxjs6

我正在调用一个API,该API返回一个JSON对象。我需要将此对象映射到数组。

下面是我的代码,但是在API调用之后,都没有得到任何响应,也没有任何错误。

export class Features {
  MenuId: number;
  MenuName: string;
  Description: string;
  RoutePath: string;
}

featureList: Features[] = [];
 constructor(private http: HttpClient)

 getFeatureListByLoggedInUser(userID: number) { debugger;       
    return this.http.get(this.myAppUrl + "api/Employee/GetMenusByUID/" + userID)     
      .pipe(
      map(
        (data: any[]) => {
        debugger;
        this.featureList = data;
        //return true;
      }), catchError(error => {
        debugger;
        return throwError('Something went wrong!')
      })
    );
 }

也尝试了下面的代码,但它给了我一个错误:

  

类型对象不可分配为类型“ any []”

 featureList: Array<any> = [];

 getFeatureListByLoggedInUser(userID: number) { debugger;  
    return this.http.get(this.myAppUrl + "api/Employee/GetMenusByUID/" + userID)
      .subscribe(
        data => {
          debugger;
          this.featureList = data;            
      });
 }

编辑:

 return this.http.get<Array<Features>>(this.myAppUrl + "api/Employee/GetMenusByUID/" + userID)   
      .subscribe(
        data => {
          debugger;
          //this.featureList = data;  
      });

1 个答案:

答案 0 :(得分:1)

您不是从.map()返回。您应该从服务中退回this.featureList

getFeatureListByLoggedInUser(userID: number) { debugger;       
    return this.http.get(this.myAppUrl + "api/Employee/GetMenusByUID/" + userID)     
      .pipe(
      map(
        (data: any[]) => {
        debugger;
       return this.featureList = data;
      }), catchError(error => {
        debugger;
        return throwError('Something went wrong!')
      })
    );
 }

编辑

在您的代码中map似乎也不必要,因为您没有在那儿操纵任何东西。您可以将其保留,并保留catchError来处理错误。

getFeatureListByLoggedInUser(userID: number) {       
    return this.http.get(this.myAppUrl + "api/Employee/GetMenusByUID/" + userID)     
      .pipe(
           catchError(error => {
            return throwError('Something went wrong!')
      })
    );
 }

在您的组件中

this.service.getFeatureListByLoggedInUser(id)
      .subscribe(data => { this.featureList = data })