从Angular 9中的键:值对Object获取并执行函数



我有一个简单的组件,它所做的只是呈现一个资源列表。这些资源是从我在这个组件内部调用的一个服务中获取的。当调用该服务时,我会广播一条消息,让其他组件知道资源已添加到数据库中。我正在尝试在广播特定消息时执行特定函数。

// service/service-list/service-list.component.ts
import { Component, OnInit } from '@angular/core';
import { Service } from '../service.model'
import { HttpClient } from '@angular/common/http';
import { ServiceApi } from '../service.api';
import { MessagingService } from 'src/app/messaging.service';
import { ServiceFunctionMaps } from '../service.function.maps.model';
import { ServiceFunction } from '../service.function.model';
@Component({
selector: 'app-service-list',
templateUrl: './service-list.component.html',
styleUrls: ['./service-list.component.css']
})
export class ServiceListComponent implements OnInit {
allServices: Service[]
functionMaps: ServiceFunctionMaps = {
// serviceAdded: this.getAllServices
serviceAdded: <ServiceFunction>this.getAllServices
}
constructor(private http: HttpClient, private api: ServiceApi, private msgService: MessagingService) {
this.msgService.readMessage().subscribe(msg => {
this.functionMaps[msg]()
// The if statement works just fine
// if (msg === 'serviceAdded') {
//   this.getAllServices()
// }
})
this.msgService.cleareMessage()
}
ngOnInit(): void {
this.getAllServices()
}
private getAllServices() {
this.api.fetchAllServices().subscribe(responseData => {
this.allServices = responseData
})
}
}
// service/service-function.ts
export interface ServiceFunction {
(params?: string): void
// (params?: string): Function
// (params?: string): () => void
}
// service/service-function-maps.model.ts
import { ServiceFunction } from './service-function.model';
export interface ServiceFunctionMaps {
[key: string]: ServiceFunction
}

正如您所看到的,我想根据广播的消息动态执行一个函数。现在代码正在编译,但我在控制台中收到一个错误,就像这样…

core.js:6189 ERROR TypeError: this.functionMaps[msg] is not a function
// tsconfig.json
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"downlevelIteration": true,
"experimentalDecorators": true,
"module": "esnext",
"moduleResolution": "node",
"importHelpers": true,
"target": "es2015",
"lib": [
"es2018",
"dom"
],
"resolveJsonModule": true
},
"angularCompilerOptions": {
"fullTemplateTypeCheck": true,
"strictInjectionParameters": true
}
}

如何创建要动态执行的函数对象?

更新

两项更改解决了问题:

  1. bind(this)
// I don't need the type interface
functionMaps = {
serviceAdded: this.getAllServices.bind(this)
}
  1. if () {}。当组件第一次加载时,似乎没有声明对象
this.msgService.readMessage().subscribe(msg => {
if(this.functionMaps[msg]){
this.functionMaps[msg]();
}
})

最新更新