Reputation:
In my current project I have a user profile route which I currently have set to navigate to dynamically. That is to say that when the user navigates to that page the user's _id is passed to localStorage and then MongoDB is queried with that _id. This then loads all of the relevant user data to display and everything works well.
This presents the problem that users can't navigate to their profile directly by pasting a link in the address bar or clicking on a link passed via email or sms. There isn't even a URL to copy unless parameters are passed via ActivatedRoute. But the URL is now basically "just for show" because I am not doing anything with the parameters in the URL.
I would like to create functionality that allows for direct navigation via URL. Below is my current attempt which is not working because, I believe, the page is rendered before the API responds. How do I go about fixing this?
Thank You.
import {AfterViewInit, Component, OnInit } from '@angular/core';
import {AuthService} from '../../services/auth.service';
import {ActivatedRoute} from '@angular/router';
@Component({
selector: 'app-view-profile',
templateUrl: './view-profile.component.html',
styleUrls: ['./view-profile.component.css']
})
export class ViewProfileComponent implements OnInit, AfterViewInit{
member: any;
isAdmin: boolean;
areas: any[];
params: any;
canDisplay: boolean = false;
constructor(private authService: AuthService,
private route: ActivatedRoute) {
}
ngOnInit() {
this.isAdmin = this.authService.isAdmin();
localStorage.setItem('member_id', this.member_id);
this.getMember(this.route.snapshot.params['user_id']);
}
ngAfterViewInit() {
console.log(this.member);
}
getMember(url) {
this.authService.getProfile(url).subscribe(member => {
this.member = member;
});
}
getParams() {
this.route.params.map(params => {
console.log(params);
});
}
setMemberData() {
let tempArray = [];
tempArray = this.member.practice.split(',');
this.areas = tempArray;
}
}
Upvotes: 0
Views: 202
Reputation: 3025
You are attempting to use this.member_id before you are requesting it from your service, let alone before the service returns a value.
In ngOnInit
subscribe to ActiveRoute
and when that returns then call your authService
. (You can think of map()
as a middle-ware which transforms the response, subscribe is used to invoke the observable)
This will ensure that the member_id is available when you are passing it to your service and setting local storage.
this.route.params.subscribe(params => {
this.authService.getProfile(params.member_id).subscribe(member => {
this.member = member;
localStorage.setItem('member_id', this.member.member_id);
});
});
Upvotes: 1