我正在做一个angular项目。我有一个使用node js的红色文本文件。然后将内容存储在url中。我需要应用http get方法从服务器获取数据并将其显示在客户端。我尝试了下面的代码,但是当我点击按钮时,我没有得到显示的文件数据。有什么问题吗?
src/app/file.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class ConfigService {
constructor(private http: HttpClient) {}
getFile() {
return this.http.get('http://localhost:3000/hello');
}
}
src/app/app.component.html
<p>
<button (click)="getFile()">get data</button>
</p>
发布于 2019-11-25 17:58:45
你有一些问题。首先,您没有订阅可观察性,因此不会发生任何事情。其次,你还需要处理可观察对象,但你不需要。第三,您还没有定义在接收到数据后注入数据的位置。
...
@Injectable()
export class ConfigService {
data = {};
constructor(private http: HttpClient) { }
getFile() {
this.http.get('http://localhost:3000/hello').subscribe(result => {
this.data = result });
}
}
那你就得找个地方展示它
<p>
<button (click)="getFile()">get data</button>
<div *ngIf="data">{{ data }}</div>
</p>
https://stackoverflow.com/questions/59037393
复制