I have a angular 2 app and I'm using route to navigate between the component. To pass the data between the sibling component I'm using Observable and Subscription pattern. But how to send data with routing(I need to pass object)
app.component.ts
@Component({
providers: [DataShareService]
})
....
app.component.html
<router-outlet></router-outlet>
DataShareService
export class DataShareService {
// Observable string sources
private dataSource = new Subject<any>();
private createdPostSource = new Subject<any>();
// Observable string streams
dataSource$ = this.dataSource.asObservable();
createdPostSource$ = this.createdPostSource.asObservable();
// Service message commands
passData(data: any) {
this.dataSource.next(data);
}
passCreatedPostSource(data:IPost[]){
this.createdPostSource.next(data);
}
}
PostListComponent
@Component({
selector: 'app-post-list',
templateUrl: './post-list.component.html',
styleUrls: ['./post-list.component.css']
})
export class PostListComponent implements OnInit {
private _postUrl: string;
public posts: IPostList;
public createPost: string;
private dataSub: Subscription;
constructor(private _postService: PostService,
private _config: ConfigService,
private _logger: ErrorLogService,
private _dataShareService: DataShareService,
private _router: Router) {
}
ngOnInit(): void {
this._postUrl = this._config.get('postApiRoot');
this._postService.getPosts(this._postUrl)
.subscribe(
result => this.posts = result,
error => this._logger.logError(error)
);
this.dataSub = this._dataShareService.createdPostSource$
.subscribe(post => {
this.posts.result.unshift(post);
console.log(this.posts.result);
});
}
createResponse(post): void {
this._dataShareService.passData(post);
console.log("postlist:" + post);
}
ngOnDestroy(): void {
this.dataSub.unsubscribe();
}
}
link in html
<a [routerLink]="['/post',post.id]" (click)="createResponse(post)">{{post.title}}</a>
post-detail.component.ts
@Component({
selector: 'app-post-detail',
templateUrl: './post-detail.component.html',
styleUrls: ['./post-detail.component.css']
})
export class PostDetailComponent implements OnInit {
private _postDetailPath: string;
private dataSub: Subscription;
private _post: IPost;
constructor(private _router: Router,
private _route: ActivatedRoute,
private _config: ConfigService,
private _dataShareService: DataShareService,
private _logger: ErrorLogService) {
}
ngOnInit() {
this.dataSub = this._dataShareService.dataSource$.subscribe(
post => {
this._post = post;
console.log('post : ' + this._post);
}, error => {
console.log('errr0');
this._logger.logError(error);
},() => {console.log('post : error' )});
}
onBack(): void {
this._router.navigate(['/posts'])
}
ngOnDestroy() {
this.dataSub.unsubscribe();
}
}
unable to get the data in ngOnInit() of post-detail after redirect.
How does this works? If i don't you routing its works. but how to made it work with routing?