【发布时间】:2018-10-11 20:21:33
【问题描述】:
我有一个生成白名单和黑名单的“标签”组件变量。目前,我有一个 updateTagLists() 函数,它将更新相应的白名单和黑名单,但我必须确保在必要时调用此函数,以便白名单/黑名单正确更新。这似乎违反直觉并且感觉不正确。当 this.tags 更改时,让 this.whitelist 和 this.blacklist 自动更新的正确方法是什么?下面发布的是我的组件。
import { Component, OnInit } from '@angular/core';
import { Tag } from '../../models/tag';
import { TagService } from '../../services/tag.service';
@Component({
selector: 'app-admin',
templateUrl: './admin.component.html',
styleUrls: ['./admin.component.css']
})
export class AdminComponent implements OnInit {
tags: any;
whitelist: Tag[];
blacklist: Tag[];
constructor(
private tagService: TagService
) {}
ngOnInit() {
this.tagService.getTags(1).then((tags) => {
this.tags = tags;
this.updateTagLists
});
}
updateTagLists() {
this.whitelist = this.tags.filter((tag: Tag) => tag.isWhitelisted );
this.blacklist = this.tags.filter((tag: Tag) => !tag.isWhitelisted );
}
whitelistAll() {
// Todo: Is there a better way of doing this where we aren't specifying the exact keys needed?
let updatedTags = this.tags.filter((tag) => !tag.isWhitelisted)
updatedTags = updatedTags.map((tag) => {
return { id: tag.id, name: tag.name, isWhitelisted: true, updated: true }
});
this.tags = updatedTags.concat(this.tags.filter((tag) => tag.isWhitelisted));
this.updateTagLists();
}
blacklistAll() {
// Todo: Is there a better way of doing this where we aren't specifying the exact keys needed?
let updatedTags = this.tags.filter((tag) => tag.isWhitelisted);
updatedTags = updatedTags.map((tag) => {
return { id: tag.id, name: tag.name, isWhitelisted: false, updated: true }
});
this.tags = updatedTags.concat(this.tags.filter((tag) => !tag.isWhitelisted));
this.updateTagLists();
}
handleToggle(event) {
if (!event) return;
let foundTag = this.tags.find( (tag) => event.id === tag.id );
foundTag.isWhitelisted = !event.isWhitelisted;
foundTag.updated = true;
this.updateTagLists();
}
}
【问题讨论】:
-
当您在每个
Tag上已经有一个isWhitelisted布尔值时,为什么会有两个不同的列表。我认为这应该足够了,您应该根据点击的标签之一来切换它。