【问题标题】:Displaying the result in the page in Angular 4在 Angular 4 的页面中显示结果
【发布时间】:2018-01-31 15:27:34
【问题描述】:

我正在尝试从数据库 (Arangodb) 中提取数据并将其显示在页面上,甚至将其推送到下一页。到目前为止,我可以通过单击按钮在控制台中显示数据。但我只想在角度页面本身而不是在控制台中显示输出。

我该如何解决这个问题?

app.component.ts

import { Component } from '@angular/core';
import {Http, Response} from '@angular/http';
import 'rxjs/add/operator/map';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})

export class AppComponent implements OnInit {
title = 'app';
constructor(private http: Http) {}

server_wsdl_get(){
return this.http.get(this.apiUrl)
.map((res: Response) => res.json())
}

 client_wsdl_get() {
   this.server_wsdl_get().subscribe(data => {
   console.log(data);
   this.data = data;
   })
 }
}

app.component.html

<li>
 <button type="submit" (click)="client_wsdl_get()">test GET data</button>
</li>

我希望这个结果显示在 Angular 页面中,而不是在控制台中。

【问题讨论】:

  • 您获得的是 JSON,因此可能不是您想要在模板中打印的内容。但与您使用 http 响应 console.log 的方式相同,响应使用它来创建您想要的模板。这里没有人知道你想如何打印数据
  • 你的 client_wsdl_get() 函数是什么样的?你能把它添加到问题中吗?
  • 不确定你想做什么,但 Angular 带有一个 JSON 管道 angular.io/api/common/JsonPipe
  • 我建议通过教程学习绑定和数据访问的基础知识。您可以在此处完成教程:angular.io/tutorial
  • 问“请帮助我”的问题往往是寻求高度本地化的指导,或者在某些情况下,是不适合我们的问答形式的持续或私人帮助。它也相当模糊,最好用更具体的问题代替。请阅读Why is “Can someone help me?” not an actual question?

标签: javascript angular


【解决方案1】:

准确地说,您必须在使用前声明您的类字段 (this.data):

import {Component} from '@angular/core';
import {Http, Response} from '@angular/http';
import 'rxjs/add/operator/map';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})

export class AppComponent implements OnInit {
  data: any;
  title = 'app';

  constructor(private http: Http) {
  }

  server_wsdl_get() {
    return this.http.get(this.apiUrl)
        .map((res: Response) => res.json())
  }

  client_wsdl_get() {
    this.server_wsdl_get().subscribe(data => {
      console.log(data);
      this.data = data;
    })
  }
}

现在您可以在模板中显示您的数据:

<span>{{data?.type}}</span>

运算符?. 确保在data 尚未定义时不会出现错误(当您想获得未定义的属性时,您会获得TypeError: Cannot read property '' of undefined)。解决此问题的其他方法是提供默认数据值或使用*ngIf.

【讨论】:

  • 这不起作用..,我仍然在控制台中得到结果。
  • @yuvii_10 我想你不知道自己在做什么。请转至angular.io/tutorial
猜你喜欢
  • 1970-01-01
  • 2016-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-10
  • 1970-01-01
相关资源
最近更新 更多