班级菜单
import { QueryParam } from "./query-param";
import { QueryRouterLink } from "./query-router-link";
export class Menu {
link: string;
name: string;
queryParam: QueryParam[];
queryRouterLink?: QueryRouterLink;
}
class QueryParam
export class QueryParam {
name: string;
value: string;
}
class QueryRouterLink
export class QueryRouterLink {
[name: string]: string;
}
我的服务
import { Injectable } from "@angular/core";
import { Menu } from "../classes/menu";
import { QueryParam } from "../classes/query-param";
import { QueryRouterLink } from "../classes/query-router-link";
@Injectable({
providedIn: "root",
})
export class LinksService {
constructor() {}
queryRouterLink: QueryRouterLink;
autoMenu() {
let myMenu: Menu[] = [
{
link: `/componentOne`,
name: "ComponentOne",
queryParam: [{ name: "resource", value: "ComponentOne" }],
},
{
link: `/componentTwo`,
name: "ComponentTwo",
queryParam: [{ name: "resource", value: "ComponentTwo" }],
},
];
for (let menuItem of myMenu) {
menuItem.queryRouterLink = this.getCorrectQueryParam(
menuItem.queryParam as QueryParam[]
);
}
return myMenu;
}
getCorrectQueryParam(queryParam: QueryParam[]) {
for (let param of queryParam) {
this.queryRouterLink[param.name] = param.value;
}
return this.queryRouterLink;
}
}
getCorrectQueryParam将我的queryParam [name:'resource',value:“ ComponentTwo”]转换为通常的QueryParams [name:string]:string;控制台中的错误是无法设置未定义的属性“资源”。是不是名称未定义?还是我的功能工作不正确?
我的app.html
<mat-toolbar>
<h1
*ngFor="let item of menu"
[routerLink]="item.link"
[queryParams]="item.queryRouterLink"
>
{{ item.name }}
</h1>
</mat-toolbar>
<router-outlet></router-outlet>
我的app.ts
import { Component, OnInit } from "@angular/core";
import { LinksService } from "./services/links.service";
import { Menu } from "./classes/menu";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.scss"],
})
export class AppComponent implements OnInit {
title = "training";
menu: Menu[];
constructor(private linkS: LinksService) {}
ngOnInit() {
this.menu = this.linkS.autoMenu();
}
}
所以答案是:
import { Injectable } from "@angular/core";
import { Menu } from "../classes/menu";
import { QueryParam } from "../classes/query-param";
import { QueryRouterLink } from "../classes/query-router-link";
@Injectable({
providedIn: "root",
})
export class LinksService {
constructor() {}
queryRouterLink: QueryRouterLink; <===== wrong
autoMenu() {
let myMenu: Menu[] = [
{
link: `/componentOne`,
name: "ComponentOne",
queryParam: [{ name: "resource", value: "ComponentOne" }],
},
{
link: `/componentTwo`,
name: "ComponentTwo",
queryParam: [{ name: "resource", value: "ComponentTwo" }],
},
];
for (let menuItem of myMenu) {
menuItem.queryRouterLink = this.getCorrectQueryParam(
menuItem.queryParam as QueryParam[]
);
}
return myMenu;
}
getCorrectQueryParam(queryParam: QueryParam[]) {
let queryRouterLink: QueryRouterLink = {}; <====correct
for (let param of queryParam) {
this.queryRouterLink[param.name] = param.value;
}
return this.queryRouterLink;
}
}