我正在尝试实现一个数据服务来从 mongoDB 读取 json 数据。我能够直接在组件的 ngOnInit() 中实现该函数,但是当我尝试实现单独的数据服务时,我无法将 json 数据获取到我的组件中。
intro-animation.component.ts:
export class IntroAnimationComponent implements OnInit {
keywords: string[];
...
}
constructor(
private _http: HttpClient) {
...
}
ngOnInit() {
this._http.get('./api/keywords').subscribe(res => {
this.keywords = res['data'];
});
}
所以这工作正常,但现在我更愿意创建一个数据服务类以在其他组件上使用它以及访问数据库中的不同表。 这是我到目前为止尝试过的方法,但没有成功:
data.service.ts
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class DataService {
results: string[];
constructor(private _http: HttpClient) { }
getKeywords(): string[] {
this.getKeywordsObservable().subscribe(res => {
this.results = res['data'];
});
return this.results;
}
getKeywordsObservable(): Observable<any> {
return this._http.get("./api/keywords")
}
}
我在 app.module 中注册了该服务,但我只是不知道如何将服务中的数据获取到我的组件中。
intro-animation.component.html
<div class="keywords-container" *ngFor="let keyword of keywords">
<div class="keyword" [ngStyle]="setKeywordFontParams()">
{{ keyword.name }}
</div>
</div>
mongoDB json数据
{
"status": 200,
"data": [
{
"_id": "5a60740d94d06e102e8c2475",
"name": "Passion"
},
{
"_id": "5a60745be4b93b2c36f6a891",
"name": "Grandeur"
},
{
"_id": "5a607461e4b93b2c36f6a892",
"name": "Prestige"
}
],
"message": null
}
我对 Angular 还很陌生,希望你能为我指明正确的方向。
最佳答案
您的 dataService getKeywords()
方法进一步调用 async
的 http.get
。
因此,当您return this.results;
时,它实际上仍然是未定义
,因此您什么也得不到。
所以更好的方法是简单地从 data.service.ts 返回可观察的像:
getKeywordsObservable(): Observable<any> {
return this._http.get("./api/keywords")
}
并且,在intro-animation.component内订阅。 喜欢:
ngOnInit() {
this._dataService.getKeywordsObservable().subscribe(res => {
this.keywords = res['data'];
});
}
关于json - Angular 5 - 实现数据服务以从 MongoDB 读取 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48324997/