Method some()在Angular 8中无法按预期工作

问题描述 投票:0回答:1

我有一个Angular应用,我想为用户添加关注/取消关注功能。我正在尝试添加isFollowed标志,因此我将能够知道是否遵循了用户,并且根据该信息,我将显示2个不同的按钮:FollowUnfollow。我正在为此目的使用some()方法,但是它不起作用。它告诉我isFollowed标志是undefined,尽管它应该显示truefalse。我不明白问题出在哪里,这是我的HTML相关部分:

<button *ngIf="!isFollowing; else unfollowBtn" class="btn" id="btn-follow" (click)="follow(id)">Follow </button>
<ng-template #unfollowBtn><button class="btn" id="btn-follow" (click)="unFollow(id)">Unfollow</button></ng-template>

TS组件相关部分:

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

import { AuthenticationService } from '@services/auth.service';
import { FollowersService } from '@services/followers.service';

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

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

  ngOnInit() {
    this.id = this.route.snapshot.paramMap.get("id");
    this.authenticationService.getSpecUser(this.id).subscribe(
      (info => {
        this.user = info;
      })
    );
    this.followersService.getFollowing().subscribe(
      data => {
        this.followers = data;
        this.isFollowing = this.followers.some(d => d.id == this.user.id);
      }
    );
  }

  follow(id) {
    console.log('follow btn');
    this.followersService.follow(id).subscribe(
      (data => console.log(data))
    )
    this.isFollowing = true;
  }

  unFollow(id) {
    console.log('unFollow btn');
    this.followersService.unFollow(id).subscribe(
      (data => console.log(data))
    )
    this.isFollowing = false;
  }
}

任何帮助将不胜感激。

javascript angular
1个回答
0
投票

如果您希望每次都调用它,并确保填充了this.user。然后可以使用forkJoin

forkJoin(
    this.authenticationService.getSpecUser(this.id),
    this.followersService.getFollowing()
  ).pipe(
    map(([info, data]) => {
      // forkJoin returns an array of values, here we map those values to the objects
      this.user = info; 
      this.followers = data;                               
      this.isFollowing = this.followers.some(d => d.id == this.user.id);
    })
  );

未测试,因为我没有时间。如果您制作了StackBlitz,我们可以看到它的实际效果并从那里尝试。

希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.