在Angular 14中,可以将一个对象作为参数传递给router-outlet
指令的解决方法如下所示:
首先,确保已经安装了Angular 14,并且已经设置好了路由。
在组件的HTML模板中,使用router-outlet
指令,并将对象作为参数传递进去:
myObject
,并初始化它:import { Component } from '@angular/core';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponent {
myObject: any = { name: 'John', age: 30 };
}
data
属性来传递参数:import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { MyComponent } from './my-component.component';
const routes: Routes = [
{
path: 'my-component',
component: MyComponent,
data: { myObject: { name: 'John', age: 30 } }
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
ActivatedRoute
服务来获取参数的值:import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponent implements OnInit {
myObject: any;
constructor(private route: ActivatedRoute) { }
ngOnInit(): void {
this.myObject = this.route.snapshot.data.myObject;
}
}
这样,你就可以在Angular 14中将一个对象作为参数传递给router-outlet
指令了。