[英]Assign a value to an interface property using a function on another in angular / typescript?
I want a property value to depend on another inside the same interface in Angular 2+.我希望一个属性值依赖于 Angular 2+ 中同一接口内的另一个。 The goal is to avoid calling the same function every time I use this class inside my app.
目标是避免每次在我的应用程序中使用这个类时调用相同的函数。
Something like this:像这样的东西:
export interface PersonItem {
_id?: number;
name: string;
lastName: string;
fullName: getFullName(this.name, this.lastName)
}
function getFullName(name, surname) {
return (name + ' ' + surname);
}
You can do it like below in type script您可以在类型脚本中执行以下操作
export interface PersonItem {
_id?: number;
name: string;
lastName: string;
fullName: Function;
}
let p: PersonItem = {name:"Ankur", lastName:"shah", fullName: function(this){ return this.name + ' ' + this.lastName}};
let temp = p.fullName();
You have declared an interface.你已经声明了一个接口。 Interfaces are great for declaring what properties and functions the outside world can see on an object.
接口非常适合声明外部世界可以在对象上看到哪些属性和函数。 What they don't do is allow you you to add any implementation detail.
他们不做的是允许您添加任何实现细节。
The implementation detail either comes in the forms of functions or classes.实现细节要么以函数的形式出现,要么以类的形式出现。
You currently have a function, but want to implement it on the object itself.您当前有一个函数,但想在对象本身上实现它。 For that you can create a class that implements the interface.
为此,您可以创建一个实现该接口的类。 I would recommend that you keep your interface, and pass that around where possible.
我建议您保留您的界面,并在可能的情况下传递它。 The code that consumes an
IPersonItem
doesn't care how fullName
has been implemented, just that it exists.使用
IPersonItem
的代码并不关心fullName
是如何实现的,只关心它是否存在。
export interface IPersonItem {
_id?: number;
name: string;
lastName: string;
fullName: string;
}
export class PersonItem implements IPersonItem {
constructor(
public name: string,
public lastName: string,
public _id?: number
) {
}
get fullName() { return `${this.name} ${this.lastName}`; }
}
Some example usage:一些示例用法:
export class MyService {
getPersonItem(): IPersonItem {
return new PersonItem('first', 'last', 123);
}
}
export class MyComponent {
constructor(private myService: MyService) {}
ngOnInit() {
const person: IPersonItem = this.myService.getPersonItem();
console.log(person.fullName); // "first last"
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.