Hi I am new to angular 2+, I am trying to share data between two components but the second component is not retrieving the data from the service, it gets an empty object.
Service - using rxjs BehaviorSubject to keep the object
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class PostsService {
response: any = {};
private messageResponse = new BehaviorSubject(this.response);
currentResponse = this.messageResponse.asObservable();
constructor(private http: Http) { }
// Get all posts from the API
getAllPosts() {
return this.http.get('/api/posts')
.map(res => {
this.messageResponse.next(res.json());
return res.json();
}).catch(err => {
console.log('caught exception' + err.status);
return Observable.throw(err);
});
}
}
Component 1 - Posts. This component makes the first call to get the data, and is retrieved no problem, and updates the messageResponse.
export class PostsComponent implements OnInit {
// instantiate posts to an empty array
posts: any = [];
constructor(private postsService: PostsService) { }
ngOnInit() {
// Retrieve posts from the API
this.postsService.getAllPosts().subscribe(posts => {
this.posts = posts;
});
}
}
Component 2 - Posts 2 - This component gets the currentResponse however the log is showing an empty array.
export class Posts2Component implements OnInit {
posts: any = [];
constructor(private postsService: PostsService) { }
ngOnInit() {
this.postsService.currentResponse.subscribe(posts => {
this.posts = posts;
console.log(this.posts);
});
}
}
Whenever I view the Posts2 component I do not see any of the currentResponse data. I'm not sure what I have done wrong here?
Thanks