RateM
RateM

Reputation: 291

Dynamically create route

My app is having some roles e.g Student, Teacher, etc. I have a route defined as

const routes : Routes = [
  { path : '', component : StudentDashboard }
]

I was wondering If I can replace StudentDashboard with TeacherDashboard dynamically based on the role. The data about role is present in a service.

I tried this

const routes : Routes = [
  { path : '', component : true ? StudentDashboard : TeacherDashboard }
]

This was not giving any compilation error. But how can I fetch the role from service so that I can replace condition in ternary expression.

What I am not looking for is 1) Re routing 2) Conditional child component I am looking for manipulating route definition, I dont know if it is possible or not but giving it try

Upvotes: 0

Views: 72

Answers (2)

Ramesh Reddy
Ramesh Reddy

Reputation: 10662

Why not just put both paths in your routing module:

const routes : Routes = [
  { path : 'teacher', component : TeacherDashboard },
{path:'student', component : StudentDashboard}
];

and when you are navigating you can check from from the service:

if(yourService.role === 'student') {
 this.router.navigate(['/student']);
} else {
this.router.navigate(['/teacher']);
}

well if the path should be empty then you can use structural directive ngIf like:

<app-student *ngIf="role === 'student'"></app-student>
<app-teacher *ngIf="role === 'teacher'"></app-teacher>

In the component.ts you can get the role from service:

role: string;
ngOnInit() {
this.role = yourservice.role;
}

Upvotes: 1

Goran Gajic
Goran Gajic

Reputation: 303

I would create another general component called 'dashboard' where in this class there are 2 variables that have type TeacherDashboard and StudentDashboard.

In app-routing I would set { path : ':id', component : DashBoardComponent }

in the Dashboard

student: StudentDashboardComponent;
teacher: TeacherDashboardComponent;
role: boolean;
// httpService is the service file where u call your api
counstructor(private router: Router, private http: HttpService) {}

ngOnInit() {
    const id = this.router.url.substring(0);
    this.http.searchTeacher(id).subscribe(
        res => {
            role = true; //true for teacher and false for student
        }); // if u get err 404, it doesn't care
    this.http.searchStudent(id).subscribe(
        res => {
            role = false; //true for teacher and false for student
        },
        err => {
            console.log(err);
            ... do something...
        });
    -do your staff-
} 

U have to adapt this code to your project, but I did that in my project and it work perfectly fine, u can also optimize all this stuff combining teacherDashboard with studentDashboard and with *ngIf on the role u can do all what u want to do.

I hope I was helpful.

Upvotes: 0

Related Questions