Need Help Accessing Variable From Service In Angular 2
Passing the URL id from the last page a user was on to a service that I can reference in a dialog. issuer.service.ts Page that has the URL id I want (dashboard.component.ts) Comp
Solution 1:
you can see this example, and It's modified list:
use queryPamas to get query string, not params (DashboardComponent)
use ReplaySubject(1) to return the last urlId; it's don't have a default value, just return prev one value (IssuerService)
- get observable from getUrlid and subscribe it in components that want to show url id
exportclassIssuerService {
private urlidSource = newReplaySubject<string>(1);
constructor() {
}
changeUrlid(urlid: string) {
this.urlidSource.next(urlid);
}
getUrlid() {
returnthis.urlidSource;
}
}
exportclassDashboardComponent implements OnInit {
urlid: string;
constructor(// private route: ActivatedRoute,
private router: Router,
private issuerService: IssuerService,
// public dialog: MatDialog) { }
newUrlid() {
// Get URL IDthis.route.queryParams.subscribe((queryParam) => {
const id = queryParam['id'];
if (!id) {
return;
}
this.issuerService.changeUrlid(id);
});
}
ngOnInit() {
this.newUrlid();
this.issuerService.getUrlid().subscribe(urlid => {
this.urlid = urlid;
});
}
}
exportclassHelloComponent implements OnInit {
urlid;
constructor(
private issuerService: IssuerService
) { }
ngOnInit() {
this.issuerService.getUrlid().subscribe(urlid => {
this.urlid = urlid;
});
}
}
Solution 2:
You do not need a parameter for your get Method since you already have the value inside the service,
getUrlid() {
returnthis.currentUrlid;
}
and you can use retrieve the value in the 2nd component as follows,
this.issuerService.currentUrlid.subscribe((value: string) => {
this.urlid = value;
}
Post a Comment for "Need Help Accessing Variable From Service In Angular 2"