【问题标题】:Angular 5 - implement Data Service to read JSON from MongoDBAngular 5 - 实现数据服务以从 MongoDB 读取 JSON
【发布时间】:2018-06-27 17:51:33
【问题描述】:

我正在尝试实现一个数据服务来从 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 的新手,希望你能指出我正确的方向。

【问题讨论】:

    标签: json mongodb angular typescript angular5


    【解决方案1】:

    您的 dataService getKeywords() 方法进一步调用 http.get,即 async。 所以当你做return this.results; 它实际上仍然是undefined 所以你什么都得不到。

    所以更好的方法是简单地从 data.service.ts 返回 observable Like:

     getKeywordsObservable(): Observable<any> {
        return this._http.get("./api/keywords")
      }
    

    并且,在 intro-animation.component 中订阅。 喜欢

    ngOnInit() {
          this._dataService.getKeywordsObservable().subscribe(res => {
            this.keywords = res['data'];
          });
        }
    

    【讨论】:

    • 非常感谢您的帮助,它成功了!我对 Promises 和 Observables 的了解还不够,无法理解其背后的过程。我现在确实更深入地研究了这些主题,现在更清楚了:)
    【解决方案2】:

    您好,您可以这样做:

    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 {
    
      constructor(private _http: HttpClient) { }
    
      public getKeywords(): any {
        return this._http.get('./api/keywords').map(res => {
          return res['data'];
        });
      }
    
    }
    

    现在您可以在组件中注入此服务并将其命名为dataService.getKeywords()

    【讨论】:

      【解决方案3】:

      intro-animation.component.ts:

      import {DataService} from "<location of service>" 
      
          export class IntroAnimationComponent implements OnInit {
            keywords: string[];
      
          constructor(
            private _service: DataService) {
            ...
          }
      
          ngOnInit() {
            this._service.getKeywords().subscribe(res => {
              this.keywords = res;
            });
          }
      

      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 {
      
        constructor(private _http: HttpClient) { }
      
      
        getKeywords(): Observable<any> {
          return this._http.get("./api/keywords")
        }
      }
      

      希望这会有所帮助

      【讨论】:

        猜你喜欢
        • 2018-04-22
        • 1970-01-01
        • 1970-01-01
        • 2015-06-20
        • 1970-01-01
        • 2012-11-30
        • 2015-09-18
        • 1970-01-01
        • 2018-06-17
        相关资源
        最近更新 更多