first configure routing
import {RouteConfig, Router, ROUTER_DIRECTIVES} from 'angular2/router';
and
@RouteConfig([
{ path: '/addDisplay', component: AddDisplay, as: 'addDisplay' },
{ path: '/<secondComponent>', component: '<secondComponentName>', as: 'secondComponentAs' },
])
then in your component import and then inject Router
import {Router} from 'angular2/router'
export class AddDisplay {
constructor(private router: Router)
}
the last thing you have to do is to call
this.router.navigateByUrl('<pathDefinedInRouteConfig>');
or
this.router.navigate(['<aliasInRouteConfig>']);
@kit's answer is okay, but remember to add ROUTER_PROVIDERS
to providers in the component. Then you can redirect to another page within ngOnInit
method:
import {Component, OnInit} from 'angular2/core';
import {Router, ROUTER_PROVIDERS} from 'angular2/router'
@Component({
selector: 'loginForm',
templateUrl: 'login.html',
providers: [ROUTER_PROVIDERS]
})
export class LoginComponent implements OnInit {
constructor(private router: Router) { }
ngOnInit() {
this.router.navigate(['./SomewhereElse']);
}
}
This worked for me Angular cli 6.x:
import {Router} from '@angular/router';
constructor(private artistService: ArtistService, private router: Router) { }
selectRow(id: number): void{
this.router.navigate([`./artist-detail/${id}`]);
}
callLog(){
this.http.get('http://localhost:3000/getstudent/'+this.login.email+'/'+this.login.password)
.subscribe(data => {
this.getstud=data as string[];
if(this.getstud.length!==0) {
console.log(data)
this.route.navigate(['home']);// used for routing after importing Router
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With