app.routing.module.ts(路由模块)
const itemRoutes: Routes = [
{ path: 'item', component: ItemListComponent},
{ path: 'DetailsPage/:id', component: DetailComponent }
];
主页.ts文件
import { Router } from '@angular/router';
export class HomePage {
constructor(private router: Router)
openNavDetailsPage(item) {
this.router.navigate(['/DetailsPage', { item: item }]);
}
}
.html文件
如果你直接想通过html页面路由:
<ion-button routerLink="/DetailsPage">Log In </ion-button>
或者
<ion-button [routerLink]="['/DetailsPage', item.id]">Log In </ion-button>
详细信息.ts文件
import { ActivatedRoute, Router } from '@angular/router';
export class DetailComponent implements OnInit {
id: any;
constructor(private route: ActivatedRoute,
private router: Router) { }
ngOnInit() {
this.id = this.route.snapshot.paramMap.get('id');
}
}
除了使用 JSON
主页.ts文件
this.router.navigate(['/DetailsPage', { item: JSON.stringify(item) }]);
详细信息.ts文件
this.item = JSON.parse(this.route.snapshot.paramMap.get('item'));
另一种方式
主页.html
<div *ngFor=""let item of items"> // here items is an array
<button (click)="goToDetail(item)" class="rgt-btn">
<ion-icon slot="icon-only" name="add-circle" ></ion-icon>
</button>
</div>
主页.ts
import { NavigationExtras, Router } from '@angular/router';
export class HomePage {
constructor(private router: Router)
goToDetail(item){
let navigationExtras: NavigationExtras = item;
this.router.navigate(['/DetailsPage'], navigationExtras);
}
}
详细信息页面.ts
import { Router } from '@angular/router';
export class DetailComponent implements OnInit {
item: any;
constructor(private router: Router) {
if (this.router.getCurrentNavigation()) {
this.item = this.router.getCurrentNavigation().extras;
}
}
}
> 或在服务页面的帮助下
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class NavExtrasService {
extras: any;
constructor() { }
public setExtras(data){
this.extras = data;
}
public getExtras(){
return this.extras;
}
}
假设我正在从主页导航到详细信息页面,在页面 A 中:
this.navExtras.setExtras(extras)
this.router.navigateByUrl('detailPage');
然后在详细信息页面中,我以这种方式检索附加内容:
let newData: any;
this.newData = navExtras.getExtras();