【问题标题】:Retrive array of object from json array of object though http request typescript angular 5通过http请求typescript angular 5从对象的json数组中检索对象数组
【发布时间】:2018-10-30 10:51:33
【问题描述】:

我想从另一个 JSON 对象数组中检索对象数组,我通过 Angular 5 中的 HTTP 请求获取该对象数组,并希望在控制台中显示值。在这里我可以成功调用 HTTP 请求并能够订阅服务.

在模板中通过 *ngFor 解析时,它工作正常,但是当我直接在 typescript 文件中访问时,它在控制台中显示未定义的值。

我的 JSON 是这样的。

{"data":[
   {
   userId: 1,
   id: 1,
   title: 'Loreum ispum',
   body: 'dummy text' 
   },
   {
   userId: 1,
   id: 1,
   title: 'Loreum ispum',
   body: 'dummy text' 
   },
   {
   userId: 1,
   id: 1,
   title: 'Loreum ispum',
   body: 'dummy text' 
   }]
}

我可以通过 ngFor 在 html 文件中访问它,它给出了值,但是当我在 typescript 中访问时,例如 console.log(this.obj[data]);它显示未定义。

我需要创建一个新数组,它只有 id 和 title 字段在 angular 5 请帮忙。我的服务页面

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpResponse } from'@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
const httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
@Injectable()
export class ConfigService {
private URL: string = 'some URL';
constructor(private http:HttpClient) {}
getData(): Observable<any>  {
return this.http.get(this.URL+ '/getdata', {responseType: 'json'});
}
}

我的组件

import { Component, OnInit, Input } from '@angular/core';
import { ConfigService } from '../services/config.service';
import { FormControl } from '@angular/forms';
import { SelectionModel } from '@angular/cdk/collections';
import { FlatTreeControl } from '@angular/cdk/tree';
import { Observable, BehaviorSubject } from 'rxjs';
@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class childComponent implements OnInit {
allData: any = [];
  getALLData() {
    this.config.getData().subscribe(
      data => { this.allData= data['data']},
      err => console.error(err),
      () => console.log('done loading data')
    );
  }

  ngOnInit() {
    this.getALLData();
    console.log(this.allData);   //here its showing undefined in console
  }
}

请帮助解决这个问题

【问题讨论】:

  • 试试console.log(this.obj.data)
  • 你能显示你的组件/服务代码吗?
  • Json 里面不能有'='。你的意思是':'
  • 这是我的服务
  • export class ConfigService { constructor(private http:HttpClient) {} getFoods(): Observable { return this.http.get('jsonplaceholder.typicode.com/posts', {responseType: 'json'} ); } }

标签: json angular typescript multidimensional-array


【解决方案1】:

HTTP 服务返回一个包含数据的 response 对象。

const request = this.http.get('...');

// The subscribe triggers the HTTP request, and you can call 
// subscribe again on the same variable to trigger another HTTP request
request.subscribe((resp)=>{ 
    // this will show the response object.
    console.log(resp);
});

您应该调用takefirst 以确保完成HTTP 请求。

request.first().subscribe((resp)=>{ 
        // there are no memory leaks now
});

你应该处理错误。

request
   .first()
   .catch((err,o)=>console.error(err))
   .subscribe((resp)=>{
       // called if only successful
   });

当 HTTP 请求成功时,您可以将响应映射到来自服务器的实际数据。

request
   .first()
   .catch((err,o)=>console.error(err))
   .map((resp)=>resp.data)
   .subscribe((data)=>{
       // this will be the JSON from the server
       console.log(data);
   });

这就是我编写 HTTP 服务函数的方式。

 getFoods() {
     return this.http
                .get('....')
                .first()
                .catch((err,o)=>console.error('There was an error'))
                .map((resp)=>resp.data);
 }  

稍后在您的组件中。只有在 observable 完成后才需要记录响应数据。

 this.data = null;
 console.log('data is null', this.data);
 this.server.getFoods().subscribe((data)=>{
      this.data = data;
      console.log('data is now set', this.data);
 });
 console.log('data is still null', this.data);

我认为这回答了您的问题,因为在 HTTP 请求完成后数据是延迟加载的。

【讨论】:

    猜你喜欢
    • 2018-11-25
    • 1970-01-01
    • 2018-09-06
    • 2017-12-08
    • 2012-03-04
    • 2018-03-16
    • 1970-01-01
    • 1970-01-01
    • 2018-09-24
    相关资源
    最近更新 更多