Angular 2: Passing Data to Routes? - javascript

I am working on this angular2 project in which I am using ROUTER_DIRECTIVES to navigate from one component to other.
There are 2 components. i.e. PagesComponent & DesignerComponent.
I want to navigate from PagesComponent to DesignerComponent.
So far its routing correctly but I needed to pass page Object so designer can load that page object in itself.
I tried using RouteParams But its getting page object undefined.
below is my code:
pages.component.ts
import {Component, OnInit ,Input} from 'angular2/core';
import { GlobalObjectsService} from './../../shared/services/global/global.objects.service';
import { ROUTER_DIRECTIVES, RouteConfig } from 'angular2/router';
import { DesignerComponent } from './../../designer/designer.component';
import {RouteParams} from 'angular2/router';
#Component({
selector: 'pages',
directives:[ROUTER_DIRECTIVES,],
templateUrl: 'app/project-manager/pages/pages.component.html'
})
#RouteConfig([
{ path: '/',name: 'Designer',component: DesignerComponent }
])
export class PagesComponent implements OnInit {
#Input() pages:any;
public selectedWorkspace:any;
constructor(private globalObjectsService:GlobalObjectsService) {
this.selectedWorkspace=this.globalObjectsService.selectedWorkspace;
}
ngOnInit() { }
}
In the html, I am doing following:
<scrollable height="300" class="list-group" style="overflow-y: auto; width: auto; height: 200px;" *ngFor="#page of pages">
{{page.name}}<a [routerLink]="['Designer',{page: page}]" title="Page Designer"><i class="fa fa-edit"></i></a>
</scrollable>
In the DesignerComponent constructor I have done the following:
constructor(params: RouteParams) {
this.page = params.get('page');
console.log(this.page);//undefined
}
So far its routing correctly to designer, but when I am trying to access page Object in designer then its showing undefined.
Any solutions?

You can't pass objects using router params, only strings because it needs to be reflected in the URL. It would be probably a better approach to use a shared service to pass data around between routed components anyway.
The old router allows to pass data but the new (RC.1) router doesn't yet.
Update
data was re-introduced in RC.4 How do I pass data in Angular 2 components while using Routing?

It changes in angular 2.1.0
In something.module.ts
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { BlogComponent } from './blog.component';
import { AddComponent } from './add/add.component';
import { EditComponent } from './edit/edit.component';
import { RouterModule } from '#angular/router';
import { MaterialModule } from '#angular/material';
import { FormsModule } from '#angular/forms';
const routes = [
{
path: '',
component: BlogComponent
},
{
path: 'add',
component: AddComponent
},
{
path: 'edit/:id',
component: EditComponent,
data: {
type: 'edit'
}
}
];
#NgModule({
imports: [
CommonModule,
RouterModule.forChild(routes),
MaterialModule.forRoot(),
FormsModule
],
declarations: [BlogComponent, EditComponent, AddComponent]
})
export class BlogModule { }
To get the data or params in edit component
import { Component, OnInit } from '#angular/core';
import { Router, ActivatedRoute, Params, Data } from '#angular/router';
#Component({
selector: 'app-edit',
templateUrl: './edit.component.html',
styleUrls: ['./edit.component.css']
})
export class EditComponent implements OnInit {
constructor(
private route: ActivatedRoute,
private router: Router
) { }
ngOnInit() {
this.route.snapshot.params['id'];
this.route.snapshot.data['type'];
}
}

You can do this:
app-routing-modules.ts:
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { PowerBoosterComponent } from './component/power-booster.component';
export const routes: Routes = [
{ path: 'pipeexamples',component: PowerBoosterComponent,
data:{ name:'shubham' } },
];
#NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
export class AppRoutingModule {}
In this above route, I want to send data via a pipeexamples path to PowerBoosterComponent.So now I can receive this data in PowerBoosterComponent like this:
power-booster-component.ts
import { Component, OnInit } from '#angular/core';
import { Router, ActivatedRoute, Params, Data } from '#angular/router';
#Component({
selector: 'power-booster',
template: `
<h2>Power Booster</h2>`
})
export class PowerBoosterComponent implements OnInit {
constructor(
private route: ActivatedRoute,
private router: Router
) { }
ngOnInit() {
//this.route.snapshot.data['name']
console.log("Data via params: ",this.route.snapshot.data['name']);
}
}
So you can get the data by this.route.snapshot.data['name'].

1. Set up your routes to accept data
{
path: 'some-route',
loadChildren:
() => import(
'./some-component/some-component.module'
).then(
m => m.SomeComponentModule
),
data: {
key: 'value',
...
},
}
2. Navigate to route:
From HTML:
<a [routerLink]=['/some-component', { key: 'value', ... }> ... </a>
Or from Typescript:
import {Router} from '#angular/router';
...
this.router.navigate(
[
'/some-component',
{
key: 'value',
...
}
]
);
3. Get data from route
import {ActivatedRoute} from '#angular/router';
...
this.value = this.route.snapshot.params['key'];

Related

Angular 4: changing url, but component is not rendered

I'm trying to link a component from one component using routerLink = "selected"
const routes: Routes = [
{
path: '',
children: [
{
path: 'account',
component: AccountComponent,
children: [
{
path: 'selected',
component: SelectedComponent,
},
],
},
]
}
];
#NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class AccountSettingsRoutingModule { }
This is AccountComponent
import { Component, OnInit, AfterViewInit } from '#angular/core';
import { Router, ActivatedRoute, RouterModule } from '#angular/router';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { Http, Response, Headers } from '#angular/http';
#Component({
selector: 'app-list-accounts',
templateUrl: './accounts-list.component.html',
styleUrls: ['./accounts-list.component.scss']
})
export class AccountComponent implements OnInit {
constructor(private http: HttpClient, private router: Router) { }
ngOnInit() {}
}
The url is changing to the desired like this dashboard/account/selected, but the view is not loading.
Add <router-outlet></router-outlet> to AccountComponent. Read more in the docs.

Cannot read property 'path' of undefined in Angular 2

I'm getting error:
Cannot read property 'path' of undefined
when I go to login page.Login page is separate template from home layout.then I created login.component.ts as <router-outlet> and auth.component.ts for my login page.
But home page working fine. error occur only load separate login page:
This is my folder structure:
login.component.ts:
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor() { }
ngOnInit() { }
}
login.route.ts:
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { RouterModule, Routes } from '#angular/router';
import { NoAuthGuard } from '../no-auth-guard.service';
import { AuthComponent } from '../login/auth.component';
export const AUTH_ROUTES: Routes = [
{
path: '', component: AuthComponent,// canActivate: [NoAuthGuard]
},
{
path: 'login', component: AuthComponent,// canActivate: [NoAuthGuard]
},
{
path: 'register', component: AuthComponent,// canActivate: [NoAuthGuard]
}
]
login.route.html:
<router-outlet></router-outlet>
auth.component.ts:
import { Component, OnInit } from '#angular/core';
import { FormBuilder, FormGroup, FormControl, Validators } from '#angular/forms';
import { ActivatedRoute, Router } from '#angular/router';
import { Errors, UserService } from '../../shared';
import { UserLogin } from '../../shared/models';
#Component({
selector: 'auth-page',
styleUrls: ['./auth.component.css'],
templateUrl: './auth.component.html'
})
export class AuthComponent implements OnInit {
authLoginForm: FormGroup;
authRegisterForm: FormGroup;
constructor(private route: ActivatedRoute, private router: Router, private userService: UserService, private fb: FormBuilder) {
// use FormBuilder to create a form group
-- some code here
// end use FormBuilder to create a form group
}
ngOnInit() {}
userLogin() { }
userRegister() {}
}
app-routing.module.ts:
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { RouterModule, Routes } from '#angular/router';
import { NoAuthGuard } from './auth/no-auth-guard.service';
import { HomeAuthResolver } from './layout/home-auth-resolver.service';
import { LoginComponent, AUTH_ROUTES } from './auth/index';
import {LayoutComponent, PUBLIC_ROUTES } from './layout/index';
const routes: Routes = [
{ path: 'login', component: LoginComponent,data: { title: 'Public Views' }, children: AUTH_ROUTES },
{ path: 'register', component: LoginComponent,data: { title: 'Public Views' }, children: AUTH_ROUTES },
{ path: '', component: LayoutComponent, data: { title: 'Secure Views' }, children: PUBLIC_ROUTES },
{ path: '**', redirectTo: 'home' }
];
#NgModule({
imports: [
CommonModule,
RouterModule.forRoot(routes)
],
exports: [RouterModule]
})
export class AppRoutingModule { }
This problem lies in the ambiguity of your routing scheme. It's also worth noting the Routes is an array and thus ordered. Routes are evaluated in order they are defined in that array.
So move your empty route (path: '') in login.route.ts to the last position in the AUTH_ROUTES array.

Supplied parameters do not match any signature of call target error is thrown on Instantiating of Class

I am trying to wrap each of router.navigateByUrl in a function of a class and plan to call that function in relevant place. But doing so throwing 'Supplied parameters do not match any signature of call target'. I have followed few other links in SO but none seems to be helpful in my case
commonRouter.ts
// have wrapped navigation to home in homePage
// so wherever is needed this homePage will be called instead of
//this.router.navigateByUrl('/home');
import {Router} from '#angular/router';
export class RouterComponent{
router:any;
constructor(private rt:Router){
this.router=rt;
}
homePage(){
this.router.navigateByUrl('/home');
}
}
someComponent.ts
// Importing the newly created typescript file
import {RouterComponent} from './../../app-routing-component';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.less']
})
export class LoginComponent implements OnInit {
private ms:MainService= new MainService();
//Instantiating RouterComponent
private rt:RouterComponent = new RouterComponent(); // this line throwing error
constructor(private fb:FormBuilder) {}
someMethod(){
rt.homePage() // Calling homePage
}
//... rest of code
}
app-routing.module.ts
// module where all the paths and component are declared
import {NgModule} from "#angular/core";
import {RouterModule, Routes} from "#angular/router";
import {HomeComponent} from "./home/home/home.component";
const routes: Routes = [
{
path: 'login', component: LoginComponent,
}, {
path: 'home', component: HomeComponent,
children: [{
path: "account",
component: AccountsComponent
},{
path: '**',
component: PageNotFoundComponent
}
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {
}
Your RouterComponent requires a Router argument. Router is an injectable, thus would be resolvable if Angular knows how to handle your RouterComponent class.
It would be best to decorate your class as Injectable and inject the value at the Angular component. e.g.
import { Injectable } from '#angular/core';
import { Router } from '#angular/router';
#Injectable()
export class RouterService {
constructor(private router: Router) { }
homePage(){
this.router.navigateByUrl('/home');
}
};
Register it in your module or add as dependency to the providers field in the Component decorator and import it into your components.
import { Component } from '#angular/core';
import { RouterService } from '...';
#Component({ ... })
export class LoginComponent {
constructor(private router: RouterService) { }
toHomePage() {
this.router.homePage();
}
};
Because it is an Injectable, Angular knows how to resolve the parameters.
The choice of namingconvention for your RouterComponent class would led others to think it is decorated as an Angular component, but you are using it as a service.

Angular Server-Side Rendering with Route Resolve

I am attempting to use Server-Side Rendering in Angular (v4) to allow for better SEO.
Things work as expected until I add resolve on my route. Adding resolve causes HTML title to retain it's initial value when viewing source.
My Module:
import {
Injectable,
ModuleWithProviders,
NgModule
} from '#angular/core';
import {
ActivatedRouteSnapshot,
Resolve,
Router,
RouterModule,
RouterStateSnapshot
} from '#angular/router';
import {
Observable
} from 'rxjs/Rx';
import {
ArticleComponent
} from './article.component';
import {
Article,
ArticlesService,
UserService,
SharedModule
} from '../shared';
#Injectable()
export class ArticleResolver implements Resolve < Article > {
constructor(
private articlesService: ArticlesService,
private router: Router,
private userService: UserService
) {}
resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): any {
return this.articlesService.get(route.params['slug'])
.catch((err) => this.router.navigateByUrl('/'));
}
}
const articleRouting: ModuleWithProviders = RouterModule.forChild([{
path: 'article/:slug',
component: ArticleComponent,
resolve: {
article: ArticleResolver
},
data: {
preload: true
}
}]);
#NgModule({
imports: [
articleRouting,
SharedModule
],
declarations: [
ArticleComponent
],
providers: [
ArticleResolver
]
}) export class ArticleModule {}
My Component:
import {
Component,
OnInit
} from '#angular/core';
import {
ActivatedRoute,
Router,
} from '#angular/router';
import {
Title,
Meta
} from '#angular/platform-browser';
import {
AppComponent
} from '../app.component';
import {
Article,
} from '../shared';
#Component({
selector: 'article-page',
templateUrl: './article.component.html'
})
export class ArticleComponent implements OnInit {
article: Article;
constructor(
private route: ActivatedRoute,
private meta: Meta,
private title: Title
) {}
ngOnInit() {
this.route.data.subscribe(
(data: {
article: Article
}) => {
this.article = data.article;
}
);
this.title.setTitle(this.article.title);
}
}
I am new to Angular SSR so any guidance is greatly appreciated.
Instead of subscribing to route data, retrieve your results from the snapshot like this:
this.route.snapshot.data['article']
You also might need to register ArticlesService in your providers for the module.
As a side note, this import:
import {
Observable
} from 'rxjs/Rx';
is an RxJS antipattern. Please use the following import instead:
import {Observable} from 'rxjs/Observable';
I found that my primary service was referencing a secondary service that was attempting to return an authentication token from window.localStorage.
Attempting to access the client storage caused Angular SSR to omit the generation of source code for my component.
Thanks #Adam_P for helping me walk through it!

Lazy loaded module create multiples instance of the parent service each time is loaded

Every time I navigate from MainComponent to TestListComponent the TestListComponent constructor is triggered and a new instance of the ObservableServiceis created. When I click the link the console show the duplicated messages. Maybe is an angular issue, any help?
main.module.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import {MainRoutingModule} from "./main-routing.module";
import {MainComponent} from './main.component';
import {ObservableService} from "../../core/services/observable.service";
#NgModule({
imports: [
BrowserModule,
MainRoutingModule,
],
declarations: [MainComponent],
providers: [ObservableService],
bootstrap: [
MainComponent
]
})
export class MainModule { }
main.routing.module.ts
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
export const routes: Routes = [
{ path: 'tests', loadChildren: 'angular/app/modules/test-list/test-list.module#TestListModule'},
{ path: '**', redirectTo: '' }
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class MainRoutingModule {}
observable.service.ts
import { Injectable } from '#angular/core';
import {Subject} from "rxjs/Rx";
import 'rxjs/add/operator/map'
#Injectable()
export class ObservableService {
// Observable string sources
private changeLanguageStatus = new Subject<Object>();
// Observable string streams
changeLanguageStatus$ = this.changeLanguageStatus.asObservable();
constructor(){}
/**
* Change language event
* #param params
*/
changeLanguageEvent(params: Object){
this.changeLanguageStatus.next(params);
}
}
test-list.module.ts
import { NgModule } from '#angular/core';
import {TestListComponent} from "./test-list.component";
#NgModule({
declarations: [
TestListComponent
]
})
export class TestListModule {}
test-list.component.ts
import {Component} from '#angular/core';
import 'rxjs/Rx';
import {ObservableService} from "../../core/services/observable.service";
#Component({
moduleId: module.id,
selector: 'st-test-list',
templateUrl: 'test-list.component.html'
})
export class TestListComponent {
constructor(private observableService:ObservableService) {
observableService.changeLanguageStatus$.subscribe(
data => {
console.log('Test', data);
});
}
}
main.component.ts
import {Component, ViewChild} from '#angular/core';
import 'rxjs/Rx';
import {ObservableService} from "../../core/services/observable.service";
#Component({
moduleId: module.id,
selector: 'st-main',
templateUrl: 'main.component.html'
})
export class MainComponent {
constructor(private observableService:ObservableService) {}
changeLanguage(lang){
this.observableService.changeLanguageEvent({type: lang});
}
}
main.component.html
<!--Dynamic content-->
<router-outlet></router-outlet>
It should be expected behavior that when you navigate to a component via routing it is created and when you navigate back it is destroyed. As far as I know you are experiencing this issue because you are creating what is called an Infinite Observable i.e. you are subscribing to it and waiting for a stream of events, in your case changing language. Because you never unsubscribe from your Observable, the function subscribed to it is kept alive for each new instance of your component. Therefore, rxjs won't handle disposing of your subscription and you will have to do it yourself.
First off I'd suggest you read about Lifecycle hooks. Check out the OnInit and OnDestroy lifecycle hooks.
Use ngOnInit to subscribe to your Observable and use ngOnDestroy to unsubscribe from it as such:
import { Component, OnInit, OnDestroy } from '#angular/core';
import { Subscription } from 'rxjs/Subscription';
#Component({ .... })
export class TestListComponent implements OnInit, OnDestroy
{
private _languageSubscription : Subscription;
ngOnInit(): void
{
this._languageSubscription = observableService.changeLanguageStatus$.subscribe(
data => {
console.log('Test', data);
});
}
ngOnDestroy() : void
{
this._languageSubscription.unsubscribe();
}
}
I hope this will solve your problem.

Categories

Resources