You have two possibilities to access the path params in angular navigation. The first one, asynchronous,
is to subscribe to the Observable<ParamMap>
observable, which you can access via paramMap
method of the ActivatedRoute
.
Then use the get
method with parameter you want to get as argument, as in the example below in the ngOnInit
method:
// other imports ignored for breviyty
import { ActivatedRoute } from '@angular/router';
import { switchMap } from 'rxjs/operators';
@Component({
selector: 'app-public-snippet-details',
templateUrl: './public-snippet-details.component.html'
})
export class PublicSnippetDetailsComponent implements OnInit {
snippetId: string;
snippet$: Observable<Codelet>;
constructor(
private publicSnippetsService: PublicSnippetsService,
private userInfoStore: UserInfoStore,
private route: ActivatedRoute) {
}
ngOnInit() {
this.snippet$ = this.route.paramMap.pipe(
switchMap(params => {
this.snippetId = params.get('id');
return this.publicSnippetsService.getPublicSnippetById(this.snippetId);
})
);
}
}
The second one, synchronous, is to the snapshot
of this route (ActivatedRoute
), and directly access the parameter from the paramMap,
const bookmarkId = this.route.snapshot.paramMap.get('id');
export class BookmarkDetailsComponent implements OnInit {
// constructor and other details ignored for brevity
ngOnInit() {
this.popup = this.route.snapshot.queryParamMap.get('popup');
this.userInfoStore.getUserInfo$().subscribe(userInfo => {
this.userData$ = this.userDataStore.getUserData$();
this.bookmark = window.history.state.bookmark;
if (!window.history.state.bookmark) {
const bookmarkId = this.route.snapshot.paramMap.get('id');
this.personalBookmarksService.getPersonalBookmarkById(userInfo.sub, bookmarkId).subscribe((response) => {
this.bookmark = response;
});
}
});
}
}
Reference - https://angular.io/guide/router
Shared with from Codever.
👉 Use the Copy to mine
functionality to copy this snippet to your own personal collection and easy manage
your code snippets.
Codever is open source on Github ⭐🙏