i recommand you to create BehaviorSubject
to manage locally your Posts collection.
first things is to create Model like this :
/**
* Strong type each item of your posts api.
*/
export class PostModel {
id: string;
title: string;
descreption: string;
image_url: string;
video_id: string;
country: string;
language: string;
company: string;
date: string;
clap: string;
views: string;
username: string;
}
then you service can looks like this :
@Injectable()
export class PostService {
// Should be private and expose by magic getter, present bellow.
private _posts$ : BehaviorSubject<PostModel[]>;
constructor(private http: HttpClient) {
// We init by empty array, this means if you subscribe before ajax answer, you will receive empty array, then be notify imediatly after request is process.
this._posts$ = new BehaviorSubject([]);
// Because this data is mandatory, we ask directly from constructor.
this.loadPost();
}
private loadPost() {
this
.http
.get('http://grace-controls.com/mind-grid/mind_select.php')
.pipe(map(res => (res as PostModel[]))) // We strong type as PostModel array
.subscribe(posts => this._posts$.next(posts)); // we push data on our internal Observable.
}
// Magic getter who return Observable of PostModel array.
get posts$() : Observable<PostModel[]> {
return this._posts$.asObservable();
}
// magic getter who return Observable of {img:string} array.
get slides$(): Observable<Array<{img:string}>> {
return this._posts$.pipe(map(posts => {
return posts.map(post => {
return {
img: post.image_url
}
});
}));
}
}
Then you can consume your data everywhere on your application, just do :
export class AppComponent implements OnInit{
constructor(private postService: PostService) { }
ngOnInit() {
this.postService.posts$.subscribe(posts => {
console.log(posts);
});
// OR
this.postService.slides$.subscribe(slides => {
console.log(slides);
});
}
}
Detail : BehaviorSuject
have to be init with default value, then when consumer subscribe to it, he will always return last emitted value.
Sample : Online sample Unfortunatly, ajax request throw error from your url because your server is not over https. Anyway this online sample is to have full code ready to check.
__ UPDATE __
I have update my sample, comment HttpCall and replace it by dummy data.