如何在 Angular5 中 link Classes/Objects?
How to link Classes/Objects in Angular5?
想象一个带有卡片和类别的闪存卡学习盒。有标题的类别,有内容的卡片,linked 类别(只有一个)并且 linked 到另一张卡片。
如果不使用 Angular 5 和 Typescript 中的服务,我应该 link 他们是谁? linking 我的意思是,class 怎么能自己找出它连接到谁?
/* card.ts */
export class Card {
public id: String;
public content: String;
public link: Card;
public category: Category;
constructor(
content, category
) {
this.content = content;
this.category = category;
this.generateId();
}
private generateId(): void {
this.id = /* generate unique id */;
}
public setLink(card) {
this.link = card;
}
}
/* category.ts */
import { Card } from './card';
export class Category {
public title: String;
public slug: String;
constructor (
title
) {
this.title = title;
this.generateSlug();
this.generateId();
}
private generateId(): void {
this.id = /* generate unique id */;
}
public getCards: Card[] {
/* HERE I DO NEED HELP */
/* to magic, and find all corresponding cards to that category */
}
}
我在代码中做了标记(HERE I DO NEED HELP
),其中一个类别应该知道哪些卡片对应于该类别。稍后我只想写 Category.getCards()
来查找所选类别中的所有卡片。
最近我试图编写服务提供程序来遍历所有卡片并找到合适的卡片,但我无法将此服务注入我的 class 以利用其优势。
PS:我习惯在 PHP 中编写代码,在 Laravel 中您可以轻松地将 classes 与 n-to-n 联系起来, 1-to-n 或 n-to-1 连接。
首先,您需要确定您的类别将如何了解卡片。事实上,您只想遍历卡片数组并过滤掉属于特定类别的项目。
这看起来可以完成这项工作
public getCards(): Card[] {
return cards.filter(card => card.category === this);
}
因此,唯一的问题是您的类别如何了解 cards
数组。将它作为参数传递给 getCards()
或传递给类别的构造函数,或者如果它是全局变量,则只需导入它。这由您决定如何继续。
想象一个带有卡片和类别的闪存卡学习盒。有标题的类别,有内容的卡片,linked 类别(只有一个)并且 linked 到另一张卡片。
如果不使用 Angular 5 和 Typescript 中的服务,我应该 link 他们是谁? linking 我的意思是,class 怎么能自己找出它连接到谁?
/* card.ts */
export class Card {
public id: String;
public content: String;
public link: Card;
public category: Category;
constructor(
content, category
) {
this.content = content;
this.category = category;
this.generateId();
}
private generateId(): void {
this.id = /* generate unique id */;
}
public setLink(card) {
this.link = card;
}
}
/* category.ts */
import { Card } from './card';
export class Category {
public title: String;
public slug: String;
constructor (
title
) {
this.title = title;
this.generateSlug();
this.generateId();
}
private generateId(): void {
this.id = /* generate unique id */;
}
public getCards: Card[] {
/* HERE I DO NEED HELP */
/* to magic, and find all corresponding cards to that category */
}
}
我在代码中做了标记(HERE I DO NEED HELP
),其中一个类别应该知道哪些卡片对应于该类别。稍后我只想写 Category.getCards()
来查找所选类别中的所有卡片。
最近我试图编写服务提供程序来遍历所有卡片并找到合适的卡片,但我无法将此服务注入我的 class 以利用其优势。
PS:我习惯在 PHP 中编写代码,在 Laravel 中您可以轻松地将 classes 与 n-to-n 联系起来, 1-to-n 或 n-to-1 连接。
首先,您需要确定您的类别将如何了解卡片。事实上,您只想遍历卡片数组并过滤掉属于特定类别的项目。
这看起来可以完成这项工作
public getCards(): Card[] {
return cards.filter(card => card.category === this);
}
因此,唯一的问题是您的类别如何了解 cards
数组。将它作为参数传递给 getCards()
或传递给类别的构造函数,或者如果它是全局变量,则只需导入它。这由您决定如何继续。