ember simple auth save user profile in a session - javascript

I can't find out why the method set of session this.get('session').set('name', name); does not persist after having reloaded the page. I followed exactly what was mentioned here.
My code
//controllers/authentification.js
import Ember from 'ember';
export default Ember.Controller.extend({
session: Ember.inject.service('session'),
actions: {
authenticate() {
var this2 = this;
let {
email, motDePasse
} = this.getProperties('email', 'motDePasse');
this.get('session').authenticate('authenticator:oauth2', email, motDePasse).then(function () {
this2.store.queryRecord('membre', {
membre: {
email: email
}
}).then(function (membre) {
var nom = membre.get('nom');
this2.get('session').set('nom', nom);
console.log('name:', nom);
});
}).catch((reason) => {
this.set('errorMessage', reason.error || reason);
});
}
}
});
for the session-store/sessions.js
import Cookie from 'ember-simple-auth/session-stores/cookie';
export default Cookie.extend();
controllers/application.js
import Ember from 'ember';
import SessionService from 'ember-simple-auth/services/session';
export default Ember.Controller.extend({
session: Ember.inject.service('session'),
index: function () {
this.transitionTo('index');
}
});
template/application.js
<ul class="nav navbar-nav navbar-right">
{{#if session.isAuthenticated}}
<li>nom :{{session.nom}}</li>
<li><a {{action 'logout' on="click"}}>Deconnecter</a></li>
{{else}}
{{#link-to 'authentification' tagName="li"}}<a href>Authentification</a>{{/link-to}}
{{/if}}
</ul>
the first time i authenticate, the variable "nom" appears but once i reload the page, the variable "nom" disappears but the session stille isAuthenticated

i have found the solution , i have just to use
this2.get('session').set('.data.nom', nom);
instead of
this2.get('session').set('nom', nom);

Related

Vuex state doesn't change after login / logout

I want to show different button in Header component, based on user authentication
Header.vue
<template>
<div class="utf_right_side">
<div class="header_widget">
<router-link :to="{name:'login'}" class="button border sign-in popup-with-zoom-anim" v-if="!isAuth"><i class="fa fa-sign-in"></i>Login</router-link>
<a class="button border sign-in popup-with-zoom-anim" v-if="isAuth" href="" #click.prevent="logout" :key="componentKey"><i class="fa fa-sign-in"></i>Logout</a>
<i class="sl sl-icon-user"></i> Add Listing</div>
</div>
</template>
<script>
import {mapActions} from 'vuex'
export default {
name:"default-layout",
data(){
return {
user:this.$store.state.auth.user,
isAuth: this.$store.state.auth.authenticated,
}
},
methods:{
...mapActions({
signOut:"auth/logout"
}),
async logout() {
await axios.post('/logout').then(({data})=>{
this.signOut();
this.$parent.forceRerender();
})
},
},
}
</script>
As you can see based on the variable isAuth which comes from the vuex state I want to show different buttons, but after logging in state doesn't change and it still show the old button (before authentication). If I refresh the page manually (f5) it shows the correct button.
Login.vue:
<script>
import { mapActions } from 'vuex'
export default {
name:"login",
data(){
return {
auth:{
email:"",
password:""
},
validationErrors:{},
processing:false
}
},
methods:{
...mapActions({
signIn:'auth/login'
}),
async login(){
this.processing = true
await axios.get('/sanctum/csrf-cookie')
await axios.post('/login',this.auth).then(({data})=>{
this.signIn()
}).catch(({response})=>{
if(response.status===422){
this.validationErrors = response.data.errors
}else{
this.validationErrors = {}
alert(response.data.message)
}
}).finally(()=>{
this.processing = false
})
},
}
}
</script>
vuex auth.js which is included in index.js vuex file:
import axios from 'axios'
import router from '#/router'
export default {
namespaced: true,
state:{
authenticated:false,
user:{}
},
getters:{
authenticated(state){
return state.authenticated
},
user(state){
return state.user
}
},
mutations:{
SET_AUTHENTICATED (state, value) {
state.authenticated = value
},
SET_USER (state, value) {
state.user = value
}
},
actions:{
login({commit}){
return axios.get('/api/user').then(({data})=>{
commit('SET_USER',data)
commit('SET_AUTHENTICATED',true)
router.push({name:'home'})
}).catch(({response:{data}})=>{
commit('SET_USER',{})
commit('SET_AUTHENTICATED',false)
})
},
logout({commit}){
commit('SET_USER',{})
commit('SET_AUTHENTICATED',false)
}
}
}
So when user logs in it enters login method in auth.js and set the correct state, here:
commit('SET_USER',data)
commit('SET_AUTHENTICATED',true)|
After that it redirects to route with name home, but Header still show old button and when I refresh the page, the correct button is displayed.
Instead of store state isAuth: this.$store.state.auth.authenticated try to import getters
import { mapGetters } from 'vuex'
and use getter in computed property, which is reactive, like:
computed: {
...mapGetters({ isAuth: 'auth/authenticated' }),
},

How to pass a User Id using params as props In Vue?

Here we are:
I have a login View. The User will log in. After he login, I will get UserID and pass it to the next View(components) using props.
Login.Vue
.then(res => {if (res.status === 200){
console.log(res.data['id'])
this.$router.push({name:'Contact', params:{userID: res.data['id'] }}) }
})
Contacts.vue
export default {
name: "contact",
props:["userID"],
data() {
return {
UserID: this.$route.params.userID,
};
},
I will get The userID after the login as shown below:
However, When the page is reloaded or refreshed the UserID will be lost:
So How can I save it when the page is reloaded?
Update: :
router-> index.js
import Vue from "vue";
import VueRouter from "vue-router";
import Login from "../views/Login.vue";
import Register from "../views/Register.vue";
import Contact from "../views/Contact.vue";
Vue.use(VueRouter);
const routes = [
{
path: "/",
name: "Login",
component: Login,
props: true
},
{
path: "/register",
name: "Register",
component: Register
},
{
path: "/contact",
name: "Contact",
component: Contact,
props: true
}
];
const router = new VueRouter({
mode: "history",
base: process.env.BASE_URL,
routes
});
export default router;
Contact.vue components:
You need to use userId as a param in your rooute to be able to pass user id from URL as props to your component:
{
path: "/contact/:userId",
name: "Contact",
component: Contact,
props: true
}
See Passing props to reactive components
Well, you get user data once when you try to log in on the login page and didn't save it in the right place. simply you just can save your user data in local storage when getting the response from API.
Login.Vue
.then(res => {
if (res.status === 200) {
console.log(res.data['id'])
this.$router.push({ name:'Contact' })
localStorage.setItem('user_id', res.data['id']);
}
})
and after that, if you check your Local Storage in Application tab in your browser developer tools, you can see user_id in Local Storage.
now you can get user_id from local storage in any component you want:
Contacts.vue
export default {
name: 'Contact',
data() {
return {
UserId: localStorage.getItem('user_id');
};
},
}

How to disable autofill on ember form field

I have a form for updating the details of alumni in ember using RESTful api. Is it possible to prevent the form from auto filling the data I previously entered in the form corresponding to another record in the model?
I have these codes in my update route directory(I am using pod-structure):
controller.js
# app/alumnis/update/controller.js
import Controller from '#ember/controller';
import { get, set } from '#ember/object';
export default Controller.extend({
firstName: null,
actions: {
updateAlumni(value) {
let firstName = get(this, 'firstName');
if(firstName) {
firstName = firstName.charAt(0).toUpperCase() + firstName.slice(1).toLowerCase();
this.get('store').findRecord('alumni', value).then(function(alumni) {
alumni.set('firstName', firstName);
alumni.save();
});
}
this.transitionToRoute('alumnis.show', value)
},
},
});
route.js
# app/alumnis/update/route.js
import Route from '#ember/routing/route';
import { set } from '#ember/object';
export default Route.extend({
model(params) {
return this.store.findRecord('alumni', params.id);
},
setupController(controller, model) {
set(controller, 'alumni', model);
}
});
template.hbs
# app/alumnis/update/template.hbs
<form class="alumniForm" {{action "updateAlumni" on="submit"}}>
<div class="form-group">
<h3>First Name : {{input name="firstName" type="text" value=firstName placeholder=alumni.firstName autocomplete="off"}}</h3>
</div>
<button class="btn btn-primary" {{action "updateAlumni" alumni.id}}>Submit</button>
</form>
router.js
# app/router.js
import EmberRouter from '#ember/routing/router';
import config from './config/environment';
const Router = EmberRouter.extend({
location: config.locationType,
rootURL: config.rootURL
});
Router.map(function() {
this.route('alumnis', function() {
this.route('show', {path: '/:id'});
this.route('add', {path: '/add'});
this.route('update', {path: '/:id/update'});
});
});
export default Router;
On the first rendering of update route after every reloading, no form fields are filled automatically. But, once we enter data to the firstName input field, it is rendered to form field in update page of any other record in the model alumni.
Properties that are set in a controller in ember will remain set when you re-navigate to the page.
The logic you've shown, leads me to believe you don't even need the controller. You are modifying a model property, saving it and transitioning.
You were doing a round-about way of updating the record, The alumni record was your model, yet you were trying to re-fetch it from the store.
route.js
# app/alumnis/update/route.js
import Route from '#ember/routing/route';
import { set,get } from '#ember/object';
export default Route.extend({
model(params) {
return this.store.findRecord('alumni', params.id);
},
updateAlumni() {
let changedAttrs = get(this, 'model').changedAttributes();
if (changedAttrs.firstName) {
let firstName = get(this, 'model.firstName').toLowerCase().capitalize();
set('model.firstName', firstName);
}
get(this,'model').save()
this.transitionToRoute('alumnis.show', get(this,'model'))
}
});
template.hbs
# app/alumnis/update/template.hbs
<form class="alumniForm" {{action "updateAlumni" on="submit"}}>
<div class="form-group">
<h3>First Name : {{input name="firstName" type="text" value=model.firstName placeholder=alumni.firstName autocomplete="off"}}</h3>
</div>
<button class="btn btn-primary" {{action "updateAlumni"}}>Submit</button>
</form>
I was able to resolve the issue by changing the below codes:
controller.js
# app/alumnis/update/controller.js
import Controller from '#ember/controller';
import { get, set } from '#ember/object';
export default Controller.extend({
firstName: null,
actions: {
updateAlumni(value) {
let alumni = get(this, 'alumni');
let changedAttrs = alumni.changedAttributes();
if(changedAttrs.firstName) {
let firstName = alumni.firstName.toLowerCase().capitalize();
alumni.set('firstName', firstName);
alumni.save()
}
this.transitionToRoute('alumnis.show', value)
},
},
});
template.hbs
# app/alumnis/update/template.hbs
<form class="alumniForm" autocomplete="off" {{action "updateAlumni" on="submit"}}>
<div class="form-group">
<h3>First Name : {{input name="firstName" type="text" value=alumni.firstName}}</h3>
</div>
<button class="btn btn-primary" {{action "updateAlumni" alumni.id}}>Submit</button>
</form>
No change in app/alumnis/update/route.js

How to update navigation bar after routing on some scenario in angular2

I have a bootstrap navbar, on the right side of navigation bar, i have some links like login,logout, register
I put it on my app.component.html.ts
<div class="navbar-collapse collapse">
// Here i check if user is authenticated, display : Hello abc#gmail.com
<ul *ngIf="user" class="nav navbar-nav navbar-right">
//code in here
</ul>
// If user is not authenticated, display Login - Register
<ul *ngIf="!user" class="nav navbar-nav navbar-right">
<li><a routerLink="/register" id="registerLink">Register</a></li>
<li><a routerLink="/login" id="loginLink">Log in</a></li>
</ul>
In login.component.ts i call my Authen.Service.ts to get token that is store on localStorage
import { UrlConstants } from './core/common/url.constants';
import { LoggedInUser } from './core/domain/loggedin.user';
import { SystemConstants } from './core/common/system.constants';
#Component({
selector: 'app-login',
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
public user: any;
private isLoggedIn = false;
loginUser(valid: boolean) {
this.loading = true;
if (valid) {
const userData = {
username: this.form.controls.username.value,
password: this.form.controls.password.value
}
this._authenService.login(userData.username, userData.password).subscribe(data => {
this.user = JSON.parse(localStorage.getItem(SystemConstants.CURRENT_USER));
// If success redirect to Home view
this._router.navigate([UrlConstants.HOME]);
}, error => {
this.loading = false;
});
}
}
ngOnInit() {
}
}
Here is my Authen.Service.ts
import { Injectable } from '#angular/core';
import { Http, Headers, RequestOptions, Response } from '#angular/http';
import 'rxjs/add/operator/map';
import { SystemConstants } from '../common/system.constants';
import { LoggedInUser } from '../domain/loggedin.user';
#Injectable()
export class AuthenService {
constructor(private _http: Http) {
}
login(username: string, password: string) {
let body = "userName=" + encodeURIComponent(username) +
"&password=" + encodeURIComponent(password) +
"&grant_type=password";
let headers = new Headers();
headers.append("Content-Type", "application/x-www-form-urlencoded");
let options = new RequestOptions({ headers: headers });
return this._http.post(SystemConstants.BASE_API + '/api/oauth/token', body, options).map((response: Response) => {
let user: LoggedInUser = response.json();
if (user && user.access_token) {
localStorage.removeItem(SystemConstants.CURRENT_USER);
localStorage.setItem(SystemConstants.CURRENT_USER, JSON.stringify(user));
}
});
}
logout() {
localStorage.removeItem(SystemConstants.CURRENT_USER);
}
isUserAuthenticated(): boolean {
let user = localStorage.getItem(SystemConstants.CURRENT_USER);
if (user != null) {
return true;
}
else
return false;
}
Here is my app.component.ts
export class AppComponent implements OnInit {
// the user object got from localStore
ngOnInit() {
this.user = JSON.parse(localStorage.getItem(SystemConstants.CURRENT_USER));
console.log(this.user);
}
}
The problem i got is i cant update the navbar to change in right state (It still work, i have the token but i have to refresh the whole page to update the nav bar)
How can i update the navigation bar in angular way? Thanks
As i understood your problem it is: How to hide "login" link located on main component after user signed himself in
I can think about solution like following:
Inside your AuthService you can add public boolean member "isLoggedIn":
#Injectable()
export class AuthService {
isLoggedIn = false;
}
You can share this service between components
Inside login component you can set isLoggedIn to true after successful login
login(){
this.auth.isLoggedIn = true
}
In your app.component you can subscribe to NavigationEnd event of the router :
export class AppComponent {
constructor(
private router: Router, private auth:AuthService){}
ngOnInit() {
this.router.events.subscribe(event => {
if (event.constructor.name === "NavigationEnd") {
this.isLoggedin = this.auth.isLoggedIn;
}
})
}
}
And then, in app component template you can show "login" menu with *ngIf="!isLoggedin"
here is plunker
hope it helps...

Why is my user ID undefined when passing it into my URL?

I am building a profile page and trying to get the authenticated user data to display there. My API call works with their id, and it works on the front end if I manually enter the id into the url.
But when I try to navigate to the profile from the navbar, I receive a
400 Bad Request for URL: http://localhost:3000/users/undefined
What I can assume right now is that it's an asynchrony issue. My profile page calls the user data, but that user data isn't available in my nav component. And it seems as though I need to pass in my id param into my profile [routerLink] if I want to navigate correctly. Since my user data isn't available in my nav component, it has nothing to pass.
Is there a better approach to this? Should I be using an event emitter?
Fairly new to Angular - help much appreciated!
Profile Component
import { Component, OnInit, Input } from '#angular/core';
import { AuthService } from '.././services/auth.service';
import { UserService } from '.././services/user.service'
import { Router, ActivatedRoute } from '#angular/router';
#Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css'],
providers: [UserService]
})
export class ProfileComponent implements OnInit {
currentUser;
isAuth: boolean;
constructor(
private session: AuthService,
private router: Router,
private userService: UserService,
private route: ActivatedRoute
) {
this.session.isAuth
.subscribe((isAuth: boolean) => {
// user will be false if logged out
// or user object if logged in.
this.isAuth = isAuth;
});
if (this.session.token) {
this.isAuth = true;
console.log(this.session);
} else {
this.isAuth = false;
}
}
ngOnInit() {
this.route.params.subscribe(params => {
this.getUserDetails(params['id']);
});
}
getUserDetails(id) {
this.userService.get(id)
.subscribe((user) => {
this.currentUser = user;
console.log(this.currentUser);
});
}
}
Nav Template
Where I'm navigating to my profile page.
<nav class="navbar navbar-default">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">bnb</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li *ngIf="!isAuth"><a [routerLink]="['login']">Login</a></li>
<li *ngIf="isAuth"><a [routerLink]="['profile']"><span class="glyphicon glyphicon-user" aria-hidden="true"></span> Profile</a></li>
<li *ngIf="isAuth"><a (click)="logout()">Logout</a></li>
<li *ngIf="!isAuth"><a [routerLink]="['signup']">Signup</a></li>
</ul>
</div>
</div>
</nav>
Nav Component
import { Component, OnInit, Input } from '#angular/core';
import { AuthService } from '.././services/auth.service';
import { UserService } from '.././services/user.service';
import { Router, ActivatedRoute } from '#angular/router';
#Component({
selector: 'app-navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {
isAuth: boolean;
currentUser: any;
constructor(
private session: AuthService,
private userService: UserService,
private router: Router,
private route: ActivatedRoute
) {
this.currentUser = JSON.parse(localStorage.getItem("User"))
console.log("USER",this.currentUser) //Currently returns Null
console.log(this.session)
this.session.isAuth
.subscribe((isAuth: boolean) => {
// user will be false if logged out
// or user object if logged in.
this.isAuth = isAuth;
});
if (this.session.token) {
this.isAuth = true;
} else {
this.isAuth = false;
}
}
ngOnInit() {
}
logout() {
this.session.logout();
}
}
Router
import { Routes } from '#angular/router';
import { LoginComponent } from '../login/login.component';
import { SignupComponent } from '../signup/signup.component';
import { HomeComponent } from '../home/home.component';
import { RentalListingsComponent } from '../rental-listings/rental-listings.component';
import { SingleRentalComponent } from '../rental-listings/single-rental/single-rental.component';
import { ProfileComponent } from '../profile/profile.component'
import { AuthService } from '../services/auth.service';
export const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'login', component: LoginComponent },
{ path: 'signup', component: SignupComponent },
{ path: 'rentals', component: RentalListingsComponent },
{ path: 'listing', component: SingleRentalComponent },
{ path: 'profile/:id', component: ProfileComponent, canActivate: [AuthService] } <--profile path. I know I have to match my url paths, but don't know how to do this from the navbar.
// { path: 'home', component: HomeComponent, canActivate: [AuthService] },
{ path: '**', redirectTo: '' }
];
Thanks for providing the detail. Somewhere you need to subscribe to 'after login' or 'authentication' event, grab the user profile JSON, and save it to localstorage so you can use it anywhere you want. If you can't hook in or subscribe to one of these, then do it imperatively somewhere convenient in your code. Find out what call you can make to fetch the entire user JSON and save it as follows...
Check out my AuthService init() below. First line is this.authProvider.on('authenticated', this.onAuth);. Whatever authentication service API you are using should provide a way for you to specify a callback (providing the login token) whenever someone logs in. The onAuth callback function saves the token in localstorage and then fetchProfile(...){...} makes another call to the authentication service API to get the whole JSON user profile using the token just received this.user.getProfile(idToken, this.onProfile);. For example, I use Auth0 in projects, and my call to Auth0 API looks like this.lock.getProfile(idToken, this.onProfile); but I replaced that with an example of what your call might look like this.user.getProfile(idToken, this.onProfile); So use whatever your API uses replace in fetchProfile. Then the onProfile callback saves the entire JSON profile in a single key in local storage using this.localStorage.set('profile', profile); Then you can get it any time by calling this.localStorage.get('profile').
Do not provide UserService through the lazy-loaded ProfileComponent. That creates a separate branch on the dependency injection tree you might not want. See https://angular-2-training-book.rangle.io/handout/modules/shared-modules-di.html Import the UserService in a top-level module like AppModule or SharedModule and provide it there. No need to export it if it's in AppModule.
app.module.ts
...
#NgModule({
imports: [
...
UserService,
...
]
providers: [
...
UserService,
...
]
Handle Auth related stuff in Auth, not Profile. Profile seems visual/implementation-specific (e.g. it has a template). Here is a code snippet example.
auth.service.ts
#Injectable()
export class Auth {
userProfile: UserProfile;
constructor(
...
private localStorage: LocalStorageService,
private router: Router,
private user: UserService,
private authProvider: ...
...
) {
}
init() {
this.authProvider.on('authenticated', this.onAuth);
// Set userProfile attribute if already saved profile
this.userProfile = this.localStorage.get('profile');
setTimeout(() => { // let AppComponent listener initialize
this.localStorage.set('profile', this.userProfile);
}, 0);
}
}
onAuth = (authResult: AuthResult) => {
this.localStorage.set('id_token', authResult.idToken);
this.fetchProfile(authResult.idToken);
}
// Save current route for redirect url
login() {
this.localStorage.set('redirect_url', this.router.url);
this.authProvider.show({initialScreen: 'login'});
};
// Check if user is logged in.
authenticated() {
// Check if unexpired token.
// Searches for item in localStorage with key == 'id_token'
return this.authProvider.tokenNotExpired();
};
logout() {
this.router.navigateByUrl('');
this.userProfile = undefined; // do before localstorage
this.localStorage.remove('id_token');
this.localStorage.remove('profile');
};
fetchProfile(idToken: string) {
this.user.getProfile(idToken, this.onProfile);
}
/**
* On profile event callback.
* Save profile to LocalStorage.
* Redirect to url if present in LocalStorage.
*/
onProfile = (error: any, profile: UserProfile) => {
if (error) {
console.log(error);
return;
}
this.userProfile = profile;
this.localStorage.set('profile', profile);
// Redirect if there is a saved url to do so.
const redirectUrl: string = this.localStorage.get('redirect_url');
if (redirectUrl !== undefined) {
this.router.navigateByUrl(redirectUrl);
this.localStorage.remove('redirect_url');
}
}
Interact with localStorage through a LocalStorageService and subscribe to changes as follows.
localstorage.service.ts
import { Injectable } from '#angular/core';
import { Subject } from 'rxjs/Subject';
#Injectable()
export class LocalStorageService {
[key:string]: any;
/**
* define your localstorage variables here as observables
*/
id_token$ = new Subject();
redirect_url$ = new Subject();
profile$ = new Subject();
customer$ = new Subject();
set(key: string, value: any) {
this[key + '$'].next(value); // this will make sure to tell every subscriber about the change.
localStorage.setItem(key, JSON.stringify(value));
}
get(key: string) {
const value = localStorage.getItem(key);
return value && JSON.parse(value);
}
remove(key: string) {
this[key + '$'].next(undefined);
localStorage.removeItem(key);
}
}
Don't do so much in constructor. Example:
app.component.ts
export class AppComponent implements OnDestroy, OnInit {
webRobot: boolean = false;
private profileSub: any;
private customerSub: any;
private subscriptionSub: any;
constructor(
private analyticsService: AnalyticsService,
private auth: Auth,
private localStorage: LocalStorageService,
) {
}
ngOnInit(): void {
this.init();
}
init() {
this.auth.init(this.webRobot);
this.analytics.init(this.webRobot);
if (!this.webRobot) {
// subscribe to authed profile changes
this.profileSub =
this.localStorage.profile$.subscribe(this.onProfile);
// Subscribe to changes to Stripe customer
this.customerSub =
this.localStorage.customer$.subscribe(this.onCustomer);
}
// always delete active subscribes on destroy
ngOnDestroy() {
this.profileSub.unsubscribe();
this.customerSub.unsubscribe();
}
onProfile = (profile: UserProfile) => {
// ...do stuff
}
onCustomer= (profile: Customer) => {
// ...do stuff
}
In your profile route configuration, it is expecting the id query param
{ path: 'profile/:id', component: ProfileComponent, canActivate: [AuthService] }
<--profile path.
I know I have to match my url paths,
but don't know how to do this from the navbar.
but your navbar link is not passing the id value
<li *ngIf="isAuth"><a [routerLink]="['profile']"><span class="glyphic
you need to do something like this in your navbar
<li *ngIf="isAuth"><a [routerLink]="['profile/user.id']">

Categories