Search code examples
angularangular-ui-router

How to init angular application with certain url?


Hello and thank you for your time.

What i want to do:

  1. I have raw html/css/js website, where there are links like https://example.com/job/plumber/questons/1

  2. When user click on it, this opens angular application for question 1 for plumber category and then user can work with it.

And i don't know how to deal with it

If a set something like this in my raw html:

<a href="https://example.com/index.html"> it is just open default angular page, but how to predefine url and params for this url?

So, i guess it should be something like this =>

<a href="https://example.com/index.html#/job/plumber/questons/1">

Can you please guide me to how i can do it?

__

My app-routing.module.ts

const routes: Routes = [
  {path: '', component: QuestionPageComponent},
  {path: 'job/:jobId/questions/:id', component: QuestionPageComponent},
  {path: 'result', component: ResultPageComponent},
  // {path: '**', component: ErrorPageComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

My Nginx

server {
    listen 443 ssl;
    ssl_certificate #;
    ssl_certificate_key #;
    server_name example.com www.example.com;
    root   /home/example;
    index  main.html; // raw_html site
}

index.html just set in /home/example folder too;

I know, that something like this can help for one route:

{ path: '', redirectTo: '/job/plumber/questions/1', pathMatch: 'full' },

But i have hundred of questions.


Solution

  • First of all there is a mistake in your routes configuration. You have route with "path: ''" at first place and without pathMatch full. This means, any path containing an empty string will match! So all pathes will match this first rule. In oder to fix this, you can either add pathMatch: 'full' to it or move it to the end of your routes array.

    Regarding your question:

    <a href="https://example.com/index.html#/job/plumber/questons/1">
    

    If your angular apps is available on the root of example.com, then this would work:

    <a href="https://example.com/job/plumber/questons/1">
    

    (assuming of course you did set up the routes the right way)

    Remark: Inside of your app, you should of course use routerLink directive for links.

    If you want to somehow dynamically redirect to some route, you could also use the router service inside of your root component:

      constructor(private readonly router: Router) {
        router.navigate(...);
      }
    

    (replace dots with your routing information)

    See angular docs here: [https://angular.io/api/router/Router#navigate][1]