首页 文章

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

提问于
浏览
1

我正在调用一个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;            
      });
 }

Edit :

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

1 回答

  • 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 })
    

相关问题