简体   繁体   English

Angular 5-使用XML响应获取HTTP

[英]Angular 5 - http get with xml response

Newby needs help with error. Newby需要错误帮助。 I am requesting data via a http get request. 我通过http get请求请求数据。 The data is in xml format. 数据为xml格式。 I need to convert it to json for use in my Angular app. 我需要将其转换为json以在我的Angular应用中使用。 When I run the following code I get a error in the console "TypeError this.http.get().map is not a function. 当我运行以下代码时,在控制台中出现错误“ TypeError this.http.get()。map不是函数。

list() {
  return this.http.get(this.apiRoot).map(res => {
  let data;
  xml2js.parseString( res.toString, function (err, result) {
  console.dir(data); // Prints JSON object!
  data = result;       
  });
  return data;
  })
  .subscribe(data => { 
  console.log(data);              
  });  }

Thanks 谢谢

您需要从rxjs导入可观察对象的运算符映射。

import { map } from 'rxjs/operators';

You need to import the rxjs map operator. 您需要导入rxjs映射运算符。 With your existing code you can do: 使用现有代码,您可以执行以下操作:

import 'rxjs/add/operator/map';

You can also import the operator function itself. 您也可以导入运算符功能本身。 This is preferred. 这是首选。 See: https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md 参见: https : //github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md

import { map } from 'rxjs/operators';

...
  return this.http.get(this.apiRoot).pipe(map(res => {

If you're using the deprecated HttpModule instead of HttpClient you'll have to do an additional step to get the response text: 如果您使用的是不推荐使用的HttpModule而不是HttpClient ,则必须执行其他步骤以获取响应文本:

.pipe(
  map(res => res.text()),

If you're using HttpClient you won't need to do this. 如果您使用的是HttpClient ,则不需要这样做。


Finally, since you're using xml2js which does not support Promises or Observables you will have to wrap the call to .parseString to add it to the observable stream. 最后,由于您使用的是不支持Promises或Observables的xml2js ,因此您必须将调用包装为.parseString才能将其添加到可观察流中。 Fortunately, RxJS provides a wrapper function that does this for you: http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#static-method-bindNodeCallback . 幸运的是,RxJS提供了一个为您执行此操作的包装函数: http ://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#static-method-bindNodeCallback。

Here we use switcMap instead of map because bindNodeCallback returns an observable. 在这里,我们使用switcMap而不是map因为bindNodeCallback返回一个可观察的对象。 switchMap will flatten it for us. switchMap将为我们扁平化

import { bindNodeCallback } from 'rxjs/observable/bindNodeCallback';
import { switchMap } from 'rxjs/operators';

function list() {
  return this.http
    .get(this.apiRoot)
    .pipe(switchMap(res => bindNodeCallback(xml2js.parseString)(res)))
    .subscribe(console.log);
}

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

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