简体   繁体   English

如何将angular 5服务响应映射到JSON对象

[英]How to map the angular 5 service response to JSON object

In the earlier angular version, in our service, we could simply map the response to a JSON object as follow : 在较早的角度版本中,在我们的服务中,我们可以简单地将响应映射到JSON对象,如下所示:

import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
import { HttpClient } from '@angular/common/http';


@Injectable()
export class MakeService {
  constructor(private http:HttpClient) { }
  getMakes(){
    return this.http.get('/api/myAPI')
    .map(res=>res.json());
  }
}

However, in angular 5 we don't have HTTP anymore and we have to use HttpClient instead, what should be added to the code above to work in angular5. 但是,在angular 5中,我们不再有HTTP,而必须使用HttpClient,应该在上面的代码中添加什么才能在angular5中工作。

my component looks like : 我的组件看起来像:

  makes : any[]; 
  constructor(private makeservice: MakeService) { }

  ngOnInit() {
    this.makeservice.getMakes().subscribe(makes=>{
    this.makes=makes;
    console.log("MAKES",this.makes);
    });
  }

simply by removing the ":any[]" data type from make it will work, but I need to pass the JSON object to component from service. 只需从make中删除“:any []”数据类型即可,但是我需要将JSON对象从服务传递给组件。

Try the following, 尝试以下方法

getMakes(){
    return this.http.get('/api/myAPI')  
}

and in component, 在组件中

constructor(public data:DMakeService ){
    this.data.getMakes().subscribe(data=>{
      console.log(data);
    })
  }

You don't need to map to JSON anymore, so this is sufficient: 您不再需要映射到JSON,因此这就足够了:

getMakes(){
  return this.http.get('/api/myAPI');
}

This returns an Observable, however, not a Promise, so you'd have to subscribe the return value to get the result. 这将返回一个Observable,但是不会返回Promise,因此您必须订阅返回值才能获得结果。 If you want to keep working with promises, you can do this: 如果您想继续兑现承诺,可以执行以下操作:

getMakes(){
  return this.http.get('/api/myAPI').toPromise();
}

According here . 根据这里 You should always subscribe to any request made by httpclient 您应该始终订阅httpclient发出的任何请求

Always subscribe! 永远订阅!

An HttpClient method does not begin its HTTP request until you call subscribe() on the observable returned by that method. 直到您对由该方法返回的observable调用subscribe()为止,HttpClient方法才会开始其HTTP请求。 This is true for all HttpClient methods. 所有HttpClient方法均是如此。

const req = http.get<Heroes>('/api/heroes');
    // 0 requests made - .subscribe() not called.
    req.subscribe();
    // 1 request made.
    req.subscribe();
    // 2 requests made.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM