【发布时间】:2021-09-24 11:48:25
【问题描述】:
我是 Angular 的新手,我最近尝试使用它创建我的第一个下拉菜单,并且效果非常好。但由于它引起了很多比较,我想知道这种做法是否是不好的做法。
我有一个看起来像这样的模板:
<div id="wrapper">
<div class="dropdown-wrapper" *ngFor="let location of locations;">
<div class="dropdown-title" (click)="showDropItems(location)">{{ location }}</div>
<div *ngFor="let bot of bots;">
<div *ngIf="bot.location === location && showItems(location)" class="dropdown-item">
{{bot.id}}
</div>
</div>
</div>
在这里,我首先只渲染唯一的位置,这些位置存储在类组件中定义的位置集中。 Onclick 然后我切换位置显示地图的值,因此在下面的 div 中我可以将这些值与当前正在循环的机器人的位置值进行比较。这样,下拉项目(机器人)显示在正确的位置下,并且只有在匹配的位置被点击时才可见。机器人的数据是从 JSON 文件中获取的。
类文件如下:
constructor(private http: HttpClient, private botService: BotService) { }
public bots: Array<Bot> = [];
public locations = new Set();
public locationsShow = new Map<string, boolean>();
ngOnInit(): void {
this.getAllBots();
}
showItems(location: any)
{
return this.locationsShow.get(location);
}
showDropItems(location: any)
{
this.locationsShow.set(location, !this.locationsShow.get(location))
}
getAllBots() {
this.botService.getAllBots()
.subscribe(response => {
this.bots = response;
console.log(response);
this.bots.forEach((bot, i) =>{
this.locations.add(bot.location);
this.locationsShow.set(bot.location, false);
})
}
)
}
由于函数被经常调用,因此在遍历 for 循环时会引起很多比较,我想知道这是不好的做法还是没问题。提前致谢。
【问题讨论】:
-
不处理您的订阅绝对是个坏习惯!确保将订阅调用的结果 (this.subscription = this.obs$.subscribe()..) 保存在变量中,并在 OnDestroy -> this.subscription.unsubscribe() 中取消订阅。这样,每当组件被销毁和重新创建时,您就不会产生内存泄漏
-
有一个很好的资源可以解释您的疑问,但我认为您已经意识到您的问题。 medium.com/showpad-engineering/… 对于这么便宜的支票,我不会太担心。 .如果您关心性能,您可能想尝试 OnPush 策略
-
@michal.materowski 你说得对,感谢您提供的资源!
标签: javascript node.js angular ecmascript-6