【问题标题】:Reload component when router-link visited访问路由器链接时重新加载组件
【发布时间】:2018-03-05 18:07:06
【问题描述】:

每次访问routerLink 时,我都需要调用ngOnInIt 方法,因为我使用当前访问的链接中的ID 来绑定和检索数据库中的数据,如果没有调用该方法,我会丢失该方法数据。

这是我的init方法的一个例子(抱歉这里不知道如何使用代码sn-ps)

ngOnInit() {
    this.authService.getAuth().subscribe(auth=> {
        if(auth) {
            this.loggedInUser = auth.email;
        } else {
        }
    });

    this.teamService.getTeams().subscribe(teams => {
        this.teams = teams;
        console.log(this.teams);
        for(var i = 0; i < this.teams.length; i++) {
            if(this.teams[i].createdBy == this.loggedInUser) {
                this.myTeams.push(this.teams[i]);
            }
        }    
    });

    console.log(this.myTeams);

    this.id = this.route.snapshot.params['id'];

    //Get Team
    this.scrimService.getScrim(this.id).subscribe(scrim => {
        this.scrim = scrim;
    });

}

这是我用来访问该组件的路由器链接

 <a *ngIf="recordOwner" [routerLink]="['/edit-scrim/'+id]" class="btn btn secondary">Edit</a>

我读到了一些类似问题的答案,比如我可以使用activatedRoute.paramssubscribe 到构造函数中的数据,以便在构造函数中调用ngOnInit 方法中的所有内容,但我不知道是什么这意味着以及如何在我的场景中完成:/

编辑

id: string;
loggedInUser: string;

scrim: Scrim = {
name: '',
game: '',
time: '',
level: '',
description: '',
region: '',
platform: '',
acceptedBy: '',
acceptedDate: '',
acceptedStatus: '',
createdBy: '',
createdDate: '',
team: ''

}

teams: Team[];
myTeams: Team[] = [];
currentDate: string;
currentTime: string;

我有一个服务,它从 firebase 数据库中获取“团队”并返回一个模型数组。我正在使用当前登录用户的电子邮件地址来查找仅由当前用户创建的团队。一旦我在数组 myTeams 中有这些团队,我就会尝试使用 myTeams 列表中的团队名称填充选择 html 标记,以供用户选择。我第一次进入这个编辑稀松布页面时,选择标签中的团队填充得很好,但是如果我移动到另一个页面并使用 RouterLink 回到这个编辑稀松布页面,则不会填充选择列表,因为它没有t 再次调用 ngoninit 方法,所以如果我刷新我的网页,团队会再次填充,我猜这是因为再次调用了 ngoninit。

【问题讨论】:

    标签: angular angular-ui-router angular-router


    【解决方案1】:

    您需要像这样将activatedRoute 注入到您的构造函数中,

    constructor(private activatedRoute: ActivatedRoute) {
    this.activatedRoute.params.subscribe(
    params =>{
       this.id = params['id'];
       this.scrimService.getScrim(this.id).subscribe(scrim => {
            this.scrim = scrim;
        });
    
    }
    }
    

    【讨论】:

    • 但这不会再次调用init方法或重新加载组件:/
    • 您需要将您的api调用代码添加到另一个方法中,并在this.id = parmas['id'];之后调用该方法
    • 我更新了我的答案以包含 API 调用,看看它是否有效
    • 如果可以的话可以在FB上联系我以获得更详细的解释谢谢facebook.com/makrani
    • 您可以在这里提问,如果您需要帮助或发布另一个问题,如果您有其他问题,请将此答案标记为已接受:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-18
    相关资源
    最近更新 更多