我正在使用angular 6来开发我的电子邮件应用程序,我为用户提供了一个邮箱列表,这些用户可以单击链接转到每个邮箱。
但是,当我使用组件version A
渲染列表时,单击路由器链接将不会发生任何事情(不会触发任何路由)。但是version B
可以正常工作。 version A
和version B
均可正确呈现UI。我想知道引擎盖下发生了什么,这是getter访问器的正确行为吗?还是这是一个有角度的错误?
Angular version: 6.1.8
Browser: Chrome (desktop) version 69
Node version: v10.7.0
Platform: Mac
import { Component } from '@angular/core';
import { EmailService } from '~/email/services/email.service';
@Component({
templateUrl: '../views/email.view.html',
})
export class EmailComponent {
public constructor(private emailService: EmailService) {}
public get mailboxes(): Mailbox[] {
return this.emailService.mailboxes;
}
}
import { Component, OnInit } from '@angular/core';
import { EmailService } from '~/email/services/email.service';
@Component({
templateUrl: '../views/email.view.html',
})
export class EmailComponent implements OnInit {
public mailboxes: Mailbox[];
public constructor(private emailService: EmailService) {}
public async ngOnInit(): Promise<void> {
this.mailboxes = this.emailService.mailboxes;
}
}
@Injectable()
export class EmailService {
public get mailboxes(): Mailbox[] {
return [
{ name: 'Inbox', icon: 'inbox', link: 'inbox' },
{ name: 'Sent', icon: 'send', link: 'sent' },
{ name: 'Drafts', icon: 'drafts', link: 'drafts' },
{ name: 'Spam', icon: 'report', link: 'spam' },
{ name: 'Trash', icon: 'delete', link: 'trash' },
{ name: 'Archive', icon: 'archive', link: 'archive' },
];
}
}
<mat-nav-list>
<a mat-list-item *ngFor="let mailbox of mailboxes"
[routerLink]="['mailboxes', mailbox.link]">
<mat-icon matListIcon>{{mailbox.icon}}</mat-icon>
<h4 matLine>{{mailbox.name}}</h4>
</a>
</mat-nav-list>
答案 0 :(得分:0)
一开始可能看起来很奇怪,但是在这里,您将2个getter链接在一起,并且在您的服务中,您总是返回一个 new Array ,因此,在执行angular操作时,它会检查值是否开始更改之所以要进入无限循环,是因为数组永远更改引用,因为“永不修复”处的值始终会更改引用(在第一种方法中不是这种情况)。尝试通过以下方式更改服务:
@Injectable()
export class EmailService {
mailbox = [
{ name: 'Inbox', icon: 'inbox', link: 'inbox' },
{ name: 'Sent', icon: 'send', link: 'sent' },
{ name: 'Drafts', icon: 'drafts', link: 'drafts' },
{ name: 'Spam', icon: 'report', link: 'spam' },
{ name: 'Trash', icon: 'delete', link: 'trash' },
{ name: 'Archive', icon: 'archive', link: 'archive' },
];
public get mailboxes(): Mailbox[] {
return this.mailbox;
}
}
它将按预期工作。