How can I fix this Angular routing problem? - javascript

I need to use a JavaScript method in my Angular frontend.
I wrote a sort of controller in this way:
import * as commands from 'commands.js'
const http=require('http')
const post = (request) => { return new Promise((resolve, reject) => {
if(request.method === 'POST'){
if(request.url === '/clean'){
commands.clean();
}
}
});
};
const server=http.createServer((req,res) => {
post(req).then(body => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(body, null, 2));
}).catch(err => {
res.writeHead(403, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({msg: 'Invalid request'}, null, 2));
});
});
server.listen(3000);
Next with ng generate service home I generate a service where i wrote:
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders } from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class HomeService {
private url = "http://localhost:3000";
private httpHeader=new HttpHeaders({'Access-Control-Allow-Origin':'*'})
constructor(private http:HttpClient) { }
public clear():Observable<any>{
return this.http.post(this.url+"/clean",null,{
headers:this.httpHeader,
responseType:'text'
})
}
}
And then I tryed to use my function clear() in my home.component.ts and I use it like this:
import { Component, OnInit } from '#angular/core';
import {MatCheckboxChange} from "#angular/material/checkbox";
import {HomeService} from "../home.service";
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor(private homeservice: HomeService) {
}
[...]
async clean(){
this.homeservice.clear()
}
[...]
}
But at this point I found a problem:
When I start my app with
ng serve
My app automatic redirect in /src/home and it show me the html code write in home.component.html. In particular I do this with the default Angular routing module.
In my app-roting.module.ts the code is:
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import {HomeComponent} from "./home/home.component";
import {SettingsComponent} from "./settings/settings.component";
const routes: Routes = [
{path: 'home', component: HomeComponent},
{path: 'settings', component: SettingsComponent},
{path: '', redirectTo: 'home', pathMatch: 'full'
},
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {
}
export const routingComponents = [HomeComponent, SettingsComponent]
It works very well but when I add private homeservice: HomeService in the constractor of my home.component.ts, my app tarts to show me the app.component.html white page and I can't do nothing. How can I fix this routing problem?

I think you are missing
<router-outlet></router-outlet>
In your app.component.html

I found the problem, I missed to import in app.module.ts HttpClientModule from #angular/common/http. Now it works.

Related

Cannot find name 'module'

I am working on an Angular 2 project. I am trying to add data-table component in my project. But facing above error at the time of compilation.what needs to be done to get the required output. please guide me in a right direction.
admin-products.component.ts
import { Component, OnInit, OnDestroy } from '#angular/core';
import { ProductService } from 'src/app/product.service';
import { Subscription } from 'rxjs';
import { Product } from 'src/app/models/product';
import { DataTableResource } from 'angular-4-data-table';
#Component({
selector: 'app-admin-products',
templateUrl: './admin-products.component.html',
styleUrls: ['./admin-products.component.css']
})
export class AdminProductsComponent implements OnInit,OnDestroy {
products: Product[];
filteredProducts: any[];
subscription: Subscription;
tableResource:DataTableResource<Product>;
items: Product[] = [];
itemCount: Number;
constructor(private productService:ProductService) {
this.subscription = this.productService.getAll().
subscribe(products =>{
this.filteredProducts= this.products = products;
this.initializeTable(products);
});
}
private initializeTable(products:Product[]){
this.tableResource.query({ offset:0})
.then(items => this.items = items);
this.tableResource.count()
.then(count => this.itemCount = count);
}
reloadItems(params){
if(!this.tableResource) return;
this.tableResource.query(params)
.then(items => this.items = items);
}
filter(query: string){
this.filteredProducts = (query) ?
this.products.filter(p => p.title.toLowerCase().includes(query.toLowerCase())) :
this.products;
}
ngOnDestroy(){
this.subscription.unsubscribe()
}
ngOnInit() {
}
}
admin-products.component.html
<p>
<a routerLink="/admin/products/new" class="btn btn-primary">New Product</a>
</p>
<p>
<input
#query
(keyup)="filter(query.value)"
type="text" class="form-control" placeholder="Search...">
</p>
<data-table
[items]="items"
[itemCount]="itemCount"
(reload)="reloadItems($event)"
>
<data-table-column
[property]="'title'"
[header]="'title'"
[sortable]="true"
[resizable]="true"
>
<data-table-column
[property]="'price'"
[header]="'Price'"
[sortable]="true"
[resizable]="true"
>
<ng-template #dataTableCell let-item="item">
{{item.price | currency:'USD':true}}
</ng-template>
</data-table-column>
<data-table-column
[property]="'$key'"
>
<ng-template #dataTableCell let-item="item">
<a [routerLink]="['/admin/products', item.$key]">Edit</a>
</ng-template>
</data-table-column>
</data-table>
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import {AngularFireModule} from 'angularfire2';
import {AngularFireDatabaseModule} from 'angularfire2/database';
import {AngularFireAuthModule} from 'angularfire2/auth';
import {RouterModule} from '#angular/router';
import{NgbModule} from '#ng-bootstrap/ng-bootstrap';
import { BsNavbarComponent } from './bs-navbar/bs-navbar.component';
import { HomeComponent } from './home/home.component';
import { ProductsComponent } from './products/products.component';
import { ShoppingCartComponent } from './shopping-cart/shopping-cart.component';
import { CheckOutComponent } from './check-out/check-out.component';
import { OrderSuccessComponent } from './order-success/order-success.component';
import { MyOrdersComponent } from './my-orders/my-orders.component';
import { AdminProductsComponent } from './admin/admin-products/admin-products.component';
import { AdminOrdersComponent } from './admin/admin-orders/admin-orders.component';
import { LoginComponent } from './login/login.component';
import {FormsModule} from '#angular/forms';
import {CustomFormsModule} from 'ng2-validation';
import {DataTableModule} from 'angular-4-data-table';
import { AppComponent } from './app.component';
import { environment } from 'src/environments/environment';
import { AuthService } from './auth.service';
import { AuthGuard as AuthGuard } from './auth-guard.service';
import { UserService } from './user.service';
import { AdminAuthGuard as AdminAuthGuard } from './admin-auth-guard.service';
import { ProductFormComponent } from './admin/product-form/product-form.component';
import { CategoryService } from './category.service';
import { ProductService } from './product.service';
#NgModule({
declarations: [
AppComponent,
BsNavbarComponent,
HomeComponent,
ProductsComponent,
ShoppingCartComponent,
CheckOutComponent,
OrderSuccessComponent,
MyOrdersComponent,
AdminProductsComponent,
AdminOrdersComponent,
LoginComponent,
ShoppingCartComponent,
ProductFormComponent
],
imports: [
BrowserModule,
FormsModule,
CustomFormsModule,
DataTableModule,
AngularFireModule.initializeApp(environment.firebase),
AngularFireDatabaseModule,
AngularFireAuthModule,
NgbModule.forRoot(),
RouterModule.forRoot([
{path: '', component: HomeComponent},
{path: 'products', component: ProductsComponent},
{path: 'shopping-cart', component: ShoppingCartComponent},
{path: 'login', component: LoginComponent},
{path: 'check-out', component: CheckOutComponent,canActivate:[AuthGuard]},
{path: 'order-success', component: OrderSuccessComponent, canActivate:[AuthGuard]},
{path: 'my/orders',component: MyOrdersComponent,canActivate:[AuthGuard]},
{path: 'admin/products/new', component:ProductFormComponent,canActivate:[AuthGuard,AdminAuthGuard]},
{path: 'admin/products/:id', component:ProductFormComponent,canActivate:[AuthGuard,AdminAuthGuard]},
{path: 'admin/products', component: AdminProductsComponent,canActivate:[AuthGuard,AdminAuthGuard]},
{path: 'admin/orders', component: AdminOrdersComponent,canActivate:[AuthGuard,AdminAuthGuard]}
])
],
providers: [
AuthService,
AuthGuard,
AdminAuthGuard,
UserService,
CategoryService,
ProductService
],
bootstrap: [AppComponent]
})
export class AppModule { }
should be done to get the required output . please guide me in a right direction
This seems to be related to compiler configuration problems. You're trying to add external components and for that you need to make some modifications to your angular project like in your tsconfig.json file. These usually are provided by the library documentation. See this related question for instance: TypeScript error in Angular2 code: Cannot find name 'module'
However, since you're trying to use a table I would highly recommend you some well known Component Libraries for Angular, all of them have well documented and explained examples:
Angular Material(My favorite) - https://material.angular.io/components/table/examples
Prime NG - https://www.primefaces.org/primeng/#/table
If you decide to do that, just follow the Getting Started of any of them and you should be able to use a well built Table Component and more easily find the solution to related bugs.

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.

Angular2 is automatically redirecting to a different path

Update I have an error that makes it load wrong something with an external file that doesn't load.
So I have this problem when I go from localhost:3000/afdelingen/1 to localhost:3000/patienten/1 . The url instantly jumps back to localhost:3000/afdelingen/1 but the correct component is still loaded. I can also tell you that the ngOnInit is called twice but the onClick is only called once so this happens because the url changes. and that it works correctly when I go from localhost:3000/dashboard to localhost:3000/afdelingen/1.
Here is my app.module.ts (Sorry for dutch in the code)
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { AppComponent } from './app.component';
import {AfdelingComponent} from "./afdeling/afdeling.component";
import {FormsModule} from "#angular/forms";
import {HttpModule} from "#angular/http";
import {DashboardComponent} from "./dashboard/dashboard.component";
import {ToolbarComponent} from "./toolbar/toolbar.component";
import {AfdelingDetailComponent} from "./afdeling-detail/afdeling-detail.component";
import {Routes, RouterModule} from "#angular/router";
import {AfdelingService} from "./services/afdeling.service";
import {KamerComponent} from "./kamers/kamer.component";
import {KamerService} from "./services/kamers.service";
import {PatientViewComponent} from "./patienten/patient-view.component";
import {PatientService} from "./services/patienten.service";
const appRoutes: Routes = [
{ path: 'dashboard', component: DashboardComponent },
{ path: 'afdelingen/:id', component: AfdelingDetailComponent },
{ path: 'patienten/:id', component: PatientViewComponent },
{ path: '', component: DashboardComponent },
{ path: '**', component: DashboardComponent }
];
#NgModule({
imports: [
BrowserModule,
FormsModule,
HttpModule,
RouterModule.forRoot(appRoutes)],
declarations: [
AppComponent,
AfdelingComponent,
DashboardComponent,
ToolbarComponent,
AfdelingDetailComponent,
KamerComponent,
PatientViewComponent],
providers: [
AfdelingService,
KamerService,
PatientService
],
bootstrap: [
AppComponent ]
})
export class AppModule { }
Component that makes the call:
import {Component, OnInit} from "#angular/core";
import {Kamer} from "../kamers/kamer";
import {KamerService} from "../services/kamers.service";
import {ActivatedRoute, Params, Router} from "#angular/router";
#Component({
selector: 'afdeling-detail',
templateUrl: './app/afdeling-detail/afdeling-detail.component.html',
styleUrls: ['./app/afdeling-detail/afdeling-detail.component.css']
})
export class AfdelingDetailComponent implements OnInit{
private afdelingId:number;
private kamers:Kamer[] = [];
private kamerNr = true;
private patientView= false;
private nextTreatmentTimeView= false;
private lastTreatmentView= false;
private sanitairView = false;
private salonView= false;
private childRoomView = false;
private error:boolean;
constructor(private kamerService:KamerService, private route: ActivatedRoute,private router:Router) {}
ngOnInit() {
this.route.params
// (+) converts string 'id' to a number
.switchMap((params: Params) => this.kamerService.getKamers(+params['id'])) //switchmap zal eventuele openstaande calls als gevolg van snelle id wijzigingen door de user automatisch cancellen
.subscribe((kamers:Kamer[]) => this.kamers = kamers);
this.route.params.subscribe((params: Params) => {
this.afdelingId = params["id"];
});
}
public goBack():void{
this.router.navigate(['dashboard']);
}
public onClick(patient:number):void {
console.log("onClick");
this.router.navigate(['patienten', patient]);
}
}
Component that it correctly loads:
import {Component, OnInit} from "#angular/core";
import {ActivatedRoute, Params, Router} from "#angular/router";
import {Patient} from "./patient";
import {PatientService} from "../services/patienten.service";
import {KamerService} from "../services/kamers.service";
#Component({
selector: 'patient-view',
templateUrl: './app/patienten/patient-view.component.html',
styleUrls: ['./app/patienten/patient-view.component.css']
})
export class PatientViewComponent implements OnInit{
private patientNr:number;
private patient:Patient;
constructor(private patientService:PatientService, private route: ActivatedRoute,private router:Router) {}
ngOnInit(){
this.route.params.subscribe((params: Params) => {
this.patientNr = +params["id"];
console.log("patient nr" + this.patientNr);
});
this.route.params
// (+) converts string 'id' to a number
.switchMap((params: Params) => this.patientService.getPatient(+params['id'])) //switchmap zal eventuele openstaande calls als gevolg van snelle id wijzigingen door de user automatisch cancellen
.subscribe((patient: Patient) => this.patient = patient);
}
}
If you need anything else just tell me.
This typically means there is an error in the component you are calling. Best thing to troubleshoot is comment out all your code in the patienten nginit so its just an empty component. Then try and load it. If it does load there is a problem with your nginit.
Might want to also comment out that route params.

angular2 cannot navigate with router

I am trying to navigate to another route after users click a login button. But I can't understand what went wrong. Below is my login component.
import { Component, OnInit } from '#angular/core';
import { AngularFire, AuthProviders, AuthMethods } from 'angularfire2';
import { Router, ActivatedRoute } from '#angular/router';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor(public af: AngularFire, private router: Router) {
this.af.auth.subscribe(auth => console.log(auth));
}
login() {
this.af.auth.login({
provider: AuthProviders.Google,
method: AuthMethods.Popup,
}).then(function(res) {
console.log('login success');
console.log(res.uid);
this.router.navigateByUrl('/main') // .then(r => console.log('then: ' + r))
.then(function(resw) {
console.log('has redirect');
})
.catch(err => console.error(err)) ;
console.log('afterward');
}).catch(err => console.error(err));
}
overrideLogin() {
this.af.auth.login({
provider: AuthProviders.Anonymous,
method: AuthMethods.Anonymous,
});
}
ngOnInit() {
}
}
<p>
login works!
</p>
<button (click)="login()">Login With Google</button>
<button (click)="overrideLogin()">Login Anonymously</button>
Here is my routes:
import { LoginComponent } from './login/login.component';
import { MainComponent } from './main/main.component';
import { ModuleWithProviders } from '#angular/core';
import { Routes, RouterModule } from '#angular/router' ;
const APP_ROUTES: Routes = [
{ path: 'login', component: LoginComponent },
{ path: '', pathMatch: 'full', redirectTo: '/login'},
{ path: 'main', component: MainComponent }
];
export const appRoutingProviders: any[] = [
];
export const APP_ROUTES_PROVIDER: ModuleWithProviders = RouterModule.forRoot(APP_ROUTES);
Here is the #NgModule:
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import { AppComponent } from './app.component';
// import routing
import { appRoutingProviders, APP_ROUTES_PROVIDER } from './app.routes' ;
#NgModule({
declarations: [
AppComponent,
LoginComponent,
MainComponent
],
imports: [
BrowserModule,
// AngularFireModule.initializeApp(firebaseConfig, myFirebaseAuthConfig), // angularfire setup
FormsModule,
HttpModule,
APP_ROUTES_PROVIDER
],
providers: [appRoutingProviders],
bootstrap: [AppComponent]
})
export class AppModule { }
I got the following error. Can someone please help let me know how to fix this?
TypeError: this is null Stack trace:
LoginComponent</LoginComponent.prototype.login/<#http://localhost:4200/main.bundle.js:70294:13
Zone$1</ZoneDelegate</ZoneDelegate.prototype.invoke#http://localhost:4200/main.bundle.js:69125:19
NgZoneImpl/this.inner<.onInvoke#http://localhost:4200/main.bundle.js:56178:28
Zone$1</ZoneDelegate</ZoneDelegate.prototype.invoke#http://localhost:4200/main.bundle.js:69124:19
Zone$1</Zone</Zone.prototype.run#http://localhost:4200/main.bundle.js:69018:24
scheduleResolveOrReject/<#http://localhost:4200/main.bundle.js:69384:52
Zone$1</ZoneDelegate</ZoneDelegate.prototype.invokeTask#http://localhost:4200/main.bundle.js:69158:23
NgZoneImpl/this.inner<.onInvokeTask#http://localhost:4200/main.bundle.js:56169:28
Zone$1</ZoneDelegate</ZoneDelegate.prototype.invokeTask#http://localhost:4200/main.bundle.js:69157:23
Zone$1</Zone</Zone.prototype.runTask#http://localhost:4200/main.bundle.js:69058:28
drainMicroTaskQueue#http://localhost:4200/main.bundle.js:69290:25
ZoneTask/this.invoke#http://localhost:4200/main.bundle.js:69230:25
Arrow Function(()=>) will resolve issue as every configuration is correct.
login() {
this.af.auth.login({
provider: AuthProviders.Google,
method: AuthMethods.Popup,
}).then((res)=> { //<----changed this line
console.log('login success');
console.log(res.uid);
this.router.navigateByUrl('/main') // .then(r => console.log('then: ' + r))
.then((resw)=> { //<----changed this line
console.log('has redirect');
})
.catch(err => console.error(err)) ;
console.log('afterward');
}).catch(err => console.error(err));
}
this is special in javascript, it depends how the function was called see How to access the correct `this` context inside a callback?.
In type script if you use a fat arrow => it'll cache the this for you eg this.af.auth.login({}).then((res) => {})

Angular 2: Passing Data to Routes?

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'];

Categories

Resources