无法从控制台向html页面显示JSON API结果

时间:2018-04-04 22:16:21

标签: javascript angular rest typescript

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

select t12.id1, t12.id2, t3.id3, coalesce(t.val, 0) as val
from (select distinct id1, id2 from #temp) t12 cross join
     #temp_id3 t3 left join
     #temp t
     on t.id1 = t12.id1 and t.id2 = t12.id2 and t.id3 = t3.id3;
这是我要显示结果的页面(测试页面)(this.router.navigate(['test']);) (test.component.html)
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; 
 }
)
}
}

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

	<div class="hl1"></div>
{{names}}
{{prices}}
<div class="hl1"></div>
这是控制台的结果 enter image description here

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您尝试查看数据的方式只会在控制台上显示。您可以使用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>