角度:删除http调用内的重复元素

时间:2018-08-28 11:41:21

标签: angular typescript

我正在尝试删除重复的map函数,但看不到我的错误,它总是使我感到“ HTTP错误”

 getListType():Observable<any> {         
             return this.http.post<any>(URL, params, httpOptions)
        .pipe(                  
               map((result: any) => {      

                          returnarray=[];

                          return result.array.forEach(function(item,index,array) {

                                if (this.returnarray.indexOf(item) == -1) {                                                                         
                                      this.returnarray.push(item);
                                } 

                                if   (index === array.length -1) {                                                    
                                      console.log(this.returnarray);
                                      return  this.result.array;
                                } 
                          }); 

              }),
              catchError(err => this.handleError(err)) 
        );        
      }

      private handleError(error: HttpErrorResponse) {
            return throwError("HTTP ERROR");
      };

2 个答案:

答案 0 :(得分:0)

 getListType():any {         
         return this.http.post<any>(URL, params, httpOptions)
    .pipe(                  
          map((result: any) => {                        
                      const returnarray=[];

                      result.data.forEach(function(item,index) {

                            if (returnarray.indexOf(item) == -1) {                                                                         
                                  returnarray.push(item);
                            } 

                            if   (index === array.length -1) {                                                    
                                  console.log(returnarray);
                                  return  result.array;
                            } 
                      });
                      return returnarray;

          }),
          catchError(err => this.handleError(err)) 
    );        
  }

答案 1 :(得分:0)

  1. returnarray=[],应使用const初始化:打字稿此时应引发错误;
  2. 您可能应该使用filter而不是forEach,这将达到目的:
return result.array.filter((item,index,array) => array.indexOf(item) ==-1);