json - Angular 5 - 实现数据服务以从 MongoDB 读取 JSON

标签 json mongodb angular typescript angular5

我正在尝试实现一个数据服务来从 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() 方法进一步调用 asynchttp.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/

相关文章:

java - 使用Retrofit进行JSON解析

javascript - 更改自动完成的 JSON 输出

C# - 解析值 : {. 路径“[0].Statistics”时遇到意外字符

node.js - 如何在 Mongoose 中为子文档设置 setter?

javascript - 如何从 Java 应用程序禁用 MongoDB 上的服务器端 JavaScript

Angular 2如何将组件子组件中的方法发送到组件父组件

javascript - 难以实现拦截器来处理刷新 token

python - 如何通过 python API 将 json/pickle 文件转储和读取到 Google Drive?

json - 如何将 MongoDB 文档转换为 JSON 对象

javascript - typescript 访问修饰符