使用组件getter渲染路由器链接将无法正常工作?

时间:2018-09-23 14:31:26

标签: angular typescript getter routerlink

我正在使用angular 6来开发我的电子邮件应用程序,我为用户提供了一个邮箱列表,这些用户可以单击链接转到每个邮箱。

但是,当我使用组件version A渲染列表时,单击路由器链接将不会发生任何事情(不会触发任何路由)。但是version B可以正常工作。 version Aversion B均可正确呈现UI。我想知道引擎盖下发生了什么,这是getter访问器的正确行为吗?还是这是一个有角度的错误?

Angular version: 6.1.8
Browser: Chrome (desktop) version 69
Node version: v10.7.0
Platform: Mac

组件(版本A)

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;
    }
}

组件(B版)

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>

更新

演示链接:https://stackblitz.com/edit/angular-gitter-clsw1d

1 个答案:

答案 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;
    }
}

它将按预期工作。