In one of my Angular 2 routes\'s templates (FirstComponent) I have a button
first.component.html
You can use BehaviorSubject for sharing data between routed components. A BehaviorSubject holds one value. When it is subscribed it emits the value immediately. A Subject doesn't hold a value.
In the service.
@Injectable({
providedIn: 'root'
})
export class CustomerReportService extends BaseService {
reportFilter = new BehaviorSubject<ReportFilterVM>(null);
constructor(private httpClient: HttpClient) { super(); }
getCustomerBalanceDetails(reportFilter: ReportFilterVM): Observable<Array<CustomerBalanceDetailVM>> {
return this.httpClient.post<Array<CustomerBalanceDetailVM>>(this.apiBaseURL + 'CustomerReport/CustomerBalanceDetail', reportFilter);
}
}
In the component you can subscribe to this BehaviorSubject.
this.reportService.reportFilter.subscribe(f => {
if (f) {
this.reportFilter = f;
}
});
Note: Subject won't work here, Need to use Behavior Subject only.
I this the other approach not good for this issue.
I thing the best approach is Query-Parameter by Router
angular that have 2 way:
Passing query parameter directly
With this code you can navigate to url
by params
in your html code:
<a [routerLink]="['customer-service']" [queryParams]="{ serviceId: 99 }"></a>
Passing query parameter by
Router
You have to inject the router within your constructor
like:
constructor(private router:Router){
}
Now use of that like:
goToPage(pageNum) {
this.router.navigate(['/product-list'], { queryParams: { serviceId: serviceId} });
}
Now if you want to read from Router
in another Component
you have to use of ActivatedRoute
like:
constructor(private activateRouter:ActivatedRouter){
}
and subscribe
that:
ngOnInit() {
this.sub = this.route
.queryParams
.subscribe(params => {
// Defaults to 0 if no query param provided.
this.page = +params['serviceId'] || 0;
});
}
Pass using JSON
<a routerLink = "/link"
[queryParams] = "{parameterName: objectToPass| json }">
sample Link
</a>
use a shared service to store data with a custom index. then send that custom index with queryParam. this approach is more flexible.
// component-a : typeScript :
constructor( private DataCollector: DataCollectorService ) {}
ngOnInit() {
this.DataCollector['someDataIndex'] = data;
}
// component-a : html :
<a routerLink="/target-page"
[queryParams]="{index: 'someDataIndex'}"></a>
.
// component-b : typeScript :
public data;
constructor( private DataCollector: DataCollectorService ) {}
ngOnInit() {
this.route.queryParams.subscribe(
(queryParams: Params) => {
this.data = this.DataCollector[queryParams['index']];
}
);
}