0

I need to browse a URL direct and pass a value, such as localhost:4200/vip/mycode, then this will direct to the default page.

I have the routing.module.ts set like this:

const routes: Routes = [
  { path: 'enroll', component: EnrollComponent },
  { path: 'default', component: DefaultComponent },
  { path: 'aboutus', component: AboutusComponent },
  { path: 'overview', component: OverviewComponent },
  { path: 'contactus', component: ContactusComponent },
  { path: 'vip/:code', component: VipComponent },

];

And the vip.component.ts file like this:

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';

@Component({
  selector: 'app-vip',
  templateUrl: './vip.component.html',
  styleUrls: ['./vip.component.css']
})
export class VipComponent implements OnInit {
  public code: string;
  public APIresult: any;
  constructor(
    private _route: ActivatedRoute,
    private _router: Router,
  ) { 
    
    this._route.params.subscribe((params: Params) => {
      this.code = params.code; 
      if (this.code != null) {
        sessionStorage.setItem('code', this.code);
        alert(this.code)
      }
    })
    
  }

  ngOnInit(): void {
  }
}

But I just cant make it work when browsing localhost:4200/vip/mycode

When I do, it just takes me to the default component.

Here is my app.component.ts:

import { Component } from '@angular/core'; import { Router } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Website';
  
  constructor(
    private router: Router,
  ){  
    this.router.navigateByUrl("/default")
  }
}

Any help will be appreciated. Thanks.

1
  • 1
    When browse to /users/Jimmy, app constructor gets called, and it redirect to default. Removing this this.router.navigateByUrl("/default") should work. Commented Dec 1, 2020 at 15:47

1 Answer 1

1

you should also add this to route array so that it get redirected to default.

{ path: '', redirectTo: 'default', pathMatch: 'full' },

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.