【问题标题】:Cannot display JSON API result from console to html page无法将 JSON API 结果从控制台显示到 html 页面
【发布时间】:2018-04-04 22:16:20
【问题描述】:

无法在 html 页面中显示控制台结果 这是 TS 组件 (home.component.ts) 的代码

import { Component, OnInit } from '@angular/core';
import { Http, Response } from '@angular/http'; 
import {Router   } from '@angular/router';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  constructor( 
    
    private http: Http,
    public router:Router
    
  ) {}

  ngOnInit() {}
  
source="";
destination="";
date="";
names="";
searchCity(){
this.http.get("http://127.0.0.1:8000/restapi/?source="+this.source+"&destination="+this.destination+"&date="+this.date+"")
.subscribe(
 (res:Response) => {
   this.router.navigate(['test']);
   const searchFlight= res.json();
   console.log(searchFlight);
   //this.names = searchFlight.names; 
 }
)
}
}
这是我要显示结果的页面(测试页面)(this.router.navigate(['test']);) (test.component.html)
	<div class="hl1"></div>
{{names}}
{{prices}}
<div class="hl1"></div>

sss 是我得到的参数 (home.component.html)

<input type="text" placeholder="From ..." [(ngModel)]=source name="source">

<input type="text" placeholder="To ..." [(ngModel)]=destination name="destination">

<input type="text" class="input datepicker" value="Mm/Dd/Yy" [(ngModel)]=date name="date">

 <button (click)=searchCity() type="submit">Search</button>
这是控制台结果 enter image description here

【问题讨论】:

  • 那么test路由组件的代码在哪里?还是路由到同一个组件?
  • 搜索完后会重定向到带有控制台结果的测试html页面
  • 你能把这个放到 StackBlitz 上吗? StackBlitz

标签: javascript angular rest typescript


【解决方案1】:

Conosole.log 是在 HTML 中的控制台中显示调试打印。

要以 HTML 格式查看服务结果,您必须从响应对象中获取它们 示例:

...首先初始化变量以在 html 上查看它们

this.names = "Sample"
this.prices = 5;

...然后在你的函数中应用这段代码

this.http.get("http://127.0.0.1:8000/restapi/?source="+this.source+"&destination="+this.destination+"&date="+this.date+"")
.subscribe(
 (res:Response) => {
   this.router.navigate(['test']);
   searchFlight= res.json();
   console.log(searchFlight);

   this.names = searchFlight.names;
   this.prices = searchFlight.prices;
 }
)

... 建议:检查您的 api 结果,并检查您的问题是否只是更新 DOM

【讨论】:

    【解决方案2】:

    您尝试查看数据的方式只会在控制台上显示。您可以使用 Firebug 或 Chrome 开发人员工具 (Ctrl+Shift+I) 即可看到该对象。如果您需要在屏幕上打印,您可以执行以下操作:

    ...
    export class HomeComponent implements OnInit {
    constructor( private http: Http, public router:Router ) {}
    
    ngOnInit(){}
    
    get printObject() {return JSON.stringify(this.object)};  //set this method
    

    你可以在你的模板中使用它

    <div> {{printObject}} </div>
    

    这样做是在控制器上设置一个方法,该方法返回对象的字符串化表示。如果您有一个数组,请在您的模板中尝试这样的操作

    <ul>
     <li *ngFor="let object of array">{{object | json}}</li>
    </ul>
    

    【讨论】:

      猜你喜欢
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多