【问题标题】:Get Json from Localhost [duplicate]从本地主机获取 Json [重复]
【发布时间】:2018-09-06 05:29:17
【问题描述】:

我正在尝试在 Angular 5 中从 http://localhost:3000/clientes 获取一些 Json,并将其加载到表中。

当 Json 位于 /assets/ 时,我可以在表中加载 Json

这是general.component.ts中的代码

constructor (private httpService: HttpClient) { }
  myVals: string [];

  ngOnInit () {
    this.httpService.get('./assets/person.json').subscribe(
      data => {
        this.myVals = data as string [];   
      },
      (err: HttpErrorResponse) => {
        console.log (err.message);
      }
    );
  }

这是我桌子的主体

<tr *ngFor="let item of myVals">
                 <td class="text-center" style="width: 15px;">{{item.ID}}</td>
                 <td class="text-center" style="width: 15px;">{{item.Name}}</td>
                 <td class="text-center" style="width: 200px;">{{item.CPF}}</td>
                 <td class="text-center">{{item.body}}</td>
             </tr>

我搜索了很多,但到目前为止没有什么可以帮助我。谢谢

【问题讨论】:

  • 你有什么问题?
  • 如果在 this.myVals = data as string [] 处设置断点; this.myVals 是否正确填充?另外,在获取之后,我会用地图替换订阅。看到这个 SO:stackoverflow.com/questions/40347814/…
  • @amy8374 默认情况下,新的HttpClient 将响应格式化为JSON,因此我们不再需要使用map 解析它
  • @Vikas 很抱歉,如果不清楚。但我的问题是:如何将 localhost:3000/clientes 中的 Json 加载到表中?如果我只是替换工作代码中的 url,则不起作用
  • 控制台是否出现任何错误?这可能是一个cors问题。您的 Angular 应用程序使用哪个端口?

标签: json angular


【解决方案1】:

您可以告诉HttpClient 响应的类型,以便更轻松、更明显地使用输出。

export interface Items {
  ID: string;//change the type according to your response
  NAME: string;
  CPF:string;
}

import 进入你的general.component.ts. 然后你可以将observable 转换成Items Array

private url ='http://localhost:3000/clientes';
public myVals=[];
ngOnInit () {
    this.httpService.get<Items[]>(this.url).subscribe(
      data => {
        this.myVals = data;   
      },
      (err: HttpErrorResponse) => {
        console.log (err.message);
      }
    );
  }

【讨论】:

    猜你喜欢
    • 2014-10-24
    • 2014-06-01
    • 2012-07-28
    • 2019-07-25
    • 2014-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-09
    相关资源
    最近更新 更多