Seeking to incorporate a data service for reading json data from mongoDB, I initially implemented the function directly within the ngOnInit() of my component successfully. However, when attempting to create a separate data service, I encountered difficulties in getting the json data into my component.
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'];
});
}
While the initial implementation works well, I now aim to develop a data service class that can be utilized by other components to access various tables in my database:
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")
}
}
I have registered the service in my app.module, but I am uncertain about how to transfer the data from the service to my component.
intro-animation.component.html
<div class="keywords-container" *ngFor="let keyword of keywords">
<div class="keyword" [ngStyle]="setKeywordFontParams()">
{{ keyword.name }}
</div>
</div>
mongoDB json data
{
"status": 200,
"data": [
{
"_id": "5a60740d94d06e102e8c2475",
"name": "Passion"
},
{
"_id": "5a60745be4b93b2c36f6a891",
"name": "Grandeur"
},
{
"_id": "5a607461e4b93b2c36f6a892",
"name": "Prestige"
}
],
"message": null
}
Being relatively new to Angular, any guidance on how to proceed would be greatly appreciated.