私はわずかに異なるアプローチでこれを達成しました。私はコンポーネントに、観測可能なものを返すサービスを呼び出させました。私のコンポーネントは、作成した特定のタイプを使用することができます。私はブログのために何をしたのかを見せます。
posts.component.ts
import { Component, OnInit } from '@angular/core';
import { PostsService } from './posts.service';
import { PostComponent } from '../post/post.component'; // --> This is my custom type
import { Observable } from 'rxjs/Rx';
@Component({
selector: 'app-posts',
templateUrl: './posts.component.html',
providers: [PostsService]
})
export class PostsComponent implements OnInit {
posts: Observable<PostComponent[]>; // --> I use the type here
constructor(private _postsService: PostsService) { }
ngOnInit() {
this._postsService.getAllPosts()
.subscribe(
posts => { this.posts = posts }, // --> I add the return values here
error => { console.log(error) }
);
}
}
上記3つの主要な部分を有しています。私はカスタムタイプPostComponent
をインポートし、タイプPostComponent
のObservableにposts
を設定し、Observableが戻ってくるので、値をposts
配列に追加します。私のサービスで
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
@Injectable()
export class PostsService {
constructor(private _http: Http) {}
getAllPosts(){
return this._http.get('[INSERT API CALL]')
.map((response: Response) => response.json())
.catch(msg => Observable.throw(msg));
}
}
posts.service.tsは、私だけresponse.json
への応答をマッピングします。これは私に必要以上の情報を提供します。 I私のpost.component
post.component.ts
import { Component, Input } from '@angular/core';
@Component({
selector: 'post',
templateUrl: './post.component.html'
})
export class PostComponent{
@Input() curPost: {
'id': number,
'title': string,
'author': string,
'date': string,
'body' : string,
};
constructor() { }
}
あなたがコンポーネントにサービスからデータを取得する方法を意味するかの「フィルタ」、それを?その場合、サービスではマッピングを行い、サービスに加入することでコンポーネント内のデータを取得します。 –