Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Rc.1 router not loading "/' component

I am attempting to use the new router from the rc.0 release. (Actually using rc.1) However I can't get the outlet to load the "Welcome" component.

Here is the app.component.ts

import { Component } from '@angular/core';
import { Routes, ROUTER_DIRECTIVES} from '@angular/router';
import { HeaderComponent } from './common/header.component';
import { WelcomeComponent } from './common/welcome.component';
import { FooterComponent } from './common/footer.component';

@Component({
  selector: 'my-app',
  template: `
    <header-component> </header-component> 
        <router-outlet> </router-outlet> 
    <footer-component> <footer-component> 
  `,
  directives: [ROUTER_DIRECTIVES, HeaderComponent, WelcomeComponent, FooterComponent]
})

@Routes([
    {path: "/", component: WelcomeComponent}
]) 

export class AppComponent { 


}

Here is the main.ts

import { bootstrap }    from '@angular/platform-browser-dynamic';
import {ROUTER_PROVIDERS} from '@angular/router';
import { AppComponent } from './app.component';

bootstrap(AppComponent, [ROUTER_PROVIDERS]);

I'm not sure what I a missing, the path for / should work. index.html has the base ref set to "/" as well. I've been digging through the source to see what I a missing but not finding anything.

like image 301
Mitchell Hamann Avatar asked May 04 '16 20:05

Mitchell Hamann


3 Answers

This is a known issue https://github.com/angular/angular/issues/8409

If you have routes setup without any router links and you don't inject the router, initial navigation does not occur.

So either you inject the Router or add <a [routerLink]="..."> until this issue is fixed.

like image 57
Günter Zöchbauer Avatar answered Nov 09 '22 08:11

Günter Zöchbauer


Looks like the constructor for AppComponent needed this:

export class AppComponent { 

    constructor(private _router:Router){

    }

}

Not sure why, if anyone has an answer for that?

like image 37
Mitchell Hamann Avatar answered Nov 09 '22 08:11

Mitchell Hamann


You still need to inject it using:

constructor(private _router:Router) { }

That's called dependency injection, also known as constructor injection. Your class depends on the Router. In the toplines of your code you declared where Angular could find the dependency with an import statement. You still need to instantiate (inject) the service before you can use it. That's what you declare in the constructor.

More info about Dependency Injection here

like image 2
Starfish Avatar answered Nov 09 '22 09:11

Starfish