简体   繁体   中英

Component doesn't update after changes in URL in Angular

I have an Angular app with user page component that displays user data. Everything works fine except one thing. When I'm currently on some other user and pressing "My profile" button that redirects me to my page (registered user) using Angular RouterLink nothong changes except url in browser, if it was /user/14 it becomes /user/6 but the data in component doesn't change at all before I manually reload the page. I'm using 2 components in layout - first is the navbar component where "My profile" button is situated and second is user component where actual userdata is being displayed. Here is relevant HTML for navbar component:

<li class="nav-item sub">
  <a class="nav-link unselectable" routerLink="/user/{{user.id}}" routerLinkActive="nav-link-active"> 
    <span class="icon icon-profile"></span> my profile
  </a>
</li>

TS component:

import { Component, OnInit } from '@angular/core';
import { Router, RouterLinkActive, RouterLink } from '@angular/router';

import { User } from '@models/user.model';
import { AuthenticationService } from '@services/auth.service';

@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {
  user: User;

  constructor(private router: Router, private auth_service: AuthenticationService) {
  }

  ngOnInit() {
    this.dropdown = false;
    // console.log('init_step');
    this.subscr = this.auth_service.currentUser;
    this.auth_service.getUser().subscribe(
      (data) => {
        this.user = data;
      });
  }

  gt_myprofile() {
    let id = this.auth_service.currentUserValue.id
    this.router.navigate([`/user/${id}`]);
    this.auth_service.getUser().subscribe(
      (data) => {
        this.user = data;
      });
  }

}

And HTML for user component:

<div class="container" id="layout">
  <div class="row justify-content">
    <div class="col-xs-12 col-md-5 col-lg-4 no-gutters">
      <app-entity-card-user [user]='user'></app-entity-card-user>
      <!--send/follow-->
      <!--stats-->
      <div class="btn-group container" role="group">
        <button type="button" class="btn btn-group-element" (click)="userFollowers()">
          <p class="btn-group-element-count">
            {{user.followers_count}}
          </p>
          <p class="btn-group-element-name">
            Followers
          </p>
        </button>
        <button type="button" class="btn btn-group-element" (click)="userFollowing()">
          <p class="btn-group-element-count">
            {{user.following_count}}
          </p>
          <p class="btn-group-element-name">
            Followings
          </p>
        </button>
      </div>
    </div>
    <div class="col-xs-12 col-md-5 col-lg-5 no-gutters">
      <!--posting form-->
      <app-post-form *ngIf="owner"></app-post-form>
      <!--switcher-->
      <app-profile-wall [user]="user"></app-profile-wall>
    </div>
    <div class="col-xs-12 col-md-5 col-lg-3 no-gutters">
      <app-speciality [user]="user"></app-speciality>
      <app-skills [user]="user"></app-skills>
    </div>
  </div>
</div>

And TS part:

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from "@angular/router";

import { User } from '@models/user.model';
import { AuthenticationService } from '@services/auth.service';
import { FollowersService } from '@services/followers.service';
import { switchMap } from 'rxjs/operators';

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
  user;
  id;
  followers;
  isFollowing: boolean;
  originUser: boolean = false;
  owner;

  constructor(
    private authenticationService: AuthenticationService,
    private followersService: FollowersService,
    private router: Router,
    private route: ActivatedRoute,
  ) { }

  ngOnInit() {
    this.id = this.route.snapshot.paramMap.get("id");
    if (this.id == JSON.parse(localStorage.getItem('currentUser')).id) {
      this.originUser = true;
    } else { console.log('false')}
    this.authenticationService.getSpecUser(this.id).subscribe(
      ((info) => {
        this.user = info;
        if (this.user.id === this.authenticationService.currentUserValue.id){
          this.owner = true;
        } else {
          this.owner = false;
        }
        this.followersService.getFollowing().subscribe(
          data => {
            this.followers = data;
            this.isFollowing = this.followers.some(d => d.id == this.user.id);
          }
        );
      })
    );
  }
}

I'm aware that I should use onDestroy or onChange hooks here to achieve result that I need, but after several attempts nothing changed. I've also tried to pass user as input from navbar but it didn't help either. Any help would be appreciated.

You are accessing the snapshot, so the id will not update.

If you subscribe to the paramMap of the activatedRoute, the id will change:

this.route.paramMap.subscribe(params => {
  this.id = this.route.snapshot.paramMap.get("id");
  // do the rest here...
});

Example StackBlitz

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM