TypeScript不允许我操纵RX JS res

时间:2018-01-10 08:04:07

标签: angular typescript rxjs

我需要快速解决此问题(Angular 4):

 title:string;
 content: string;
  comment: string;

  constructor( private http: HttpClient) {}

  posts: {title: string, content: string, comments: String[]}[] = [];

  ngOnInit() {
    this.http.get('http://localhost:3003/posts').subscribe( res => {
      console.log(res))
      // can't do res.forEach (object has no forEach)
      // can't do JSON.parse(res) because res is not a string

  })
}

res的内容:

["{"title":"sadsa","content":"sadasd","comments":[]}", "{"title":"sadsa","content":"sadasd","comments":[]}", "{"title":"sadsa","content":"sadasd","comments":[]}", "{"title":"sadsa","content":"sadasd","comments":[]}", "{"title":"sadsa","content":"sadasd","comments":[]}", "{"title":"sadsa","content":"sadasd","comments":[]}", "{"title":"sadsa","content":"sadasd","comments":[]}"]

我从我的服务器发送一个数组,就像我在客户端上的数组一样,问题是,它以字符串化数组的格式出现,但出于某种原因,类型脚本不会让我处理它像一个数组,声称它是一个对象,我试图发送一个包含数组的对象,但它声称“未解决的变量”#39;。 我在这一切中缺少什么?

3 个答案:

答案 0 :(得分:2)

响应类型为Response。您可以在其上调用.input-wrapper::before { ... } 来获取内容。不,这在参考页面中没有记录,因为谷歌讨厌你。

答案 1 :(得分:1)

使用Angular Http,您可以在订阅请求之前映射响应,如下所示:

...
ngOnInit() {
   this.http.get('http://localhost:3003/posts')
       .map(toJsonFn)  // or map to you class or what have you
       .subscribe( res => {
           console.log(res))
       })
}

toJsonFn(res: Response){
    return res.json();
}
...

请注意,您可能需要从rxjx导入map运算符 - import 'rxjs/add/operator/map'

另请注意,如果您使用Angular 5 HttpClient,响应将自动解析为json。

答案 2 :(得分:0)

您的回复不是正确的json对象。使用以下代码来获取正确的json:

 ngOnInit() {
    this.http.get('http://localhost:3003/posts').subscribe( (res: any[]) => {
      console.log(res))
      let data = res.map(d => {
        return JSON.parse(d);
      });
      // data will be an array of data. Assign it to a property of component.

    })
  }

希望它会有所帮助