How should I modify the response to an HTTP request and easily access it before return it out from Observable?

前端 未结 6 624
春和景丽
春和景丽 2021-02-01 23:42

I\'m upgrading to Angular to version 5, I was using @angular/http before and now I need to update to @angular/common/http and use HttpClient

I a

6条回答
  •  南旧
    南旧 (楼主)
    2021-02-02 00:01

    My service

    import {HttpClient} from '@angular/common/http';
    
    import 'rxjs/add/operator/map';
    import 'rxjs/add/operator/catch';
    @Injectable()
    export class DataService {
        constructor(private http: HttpClient) {}
        getData()
        {
            return this.http.get('../assets/data.json').map(data=>{
                return this.process(data);
            }).catch(
                (error: Response) => {
                  return Observable.throw(error);
                });
        }
        process(data:any)  
        {
            let dataTransform:any[]=[];
            let i:number=0;
            for (let item of data)
            {
                dataTransform.push({"id":i,"key":item.key});
                i++;
            }
            return dataTransform;
        }
    }
    

    //My component

    export class AppComponent implements OnInit {
      constructor(private dataService:DataService){}
      ngOnInit(){
        this.dataService.getData().subscribe((data:any)=> {
          console.log(data);
        });
      }
    }
    

    //the asset/data.json

    [
        {"key":"uno"},
        {"key":"dos"},
        {"key":"tres"},
        {"key":"cuatro"},
        {"key":"cinco"}
    ]
    

提交回复
热议问题