【问题标题】:data only displaying after refresh in angular数据仅在角度刷新后显示
【发布时间】:2021-10-30 11:06:29
【问题描述】:

我有卡片组件、主页和探索页面。我已经在探索页面中显示了所有卡片,用户可以收藏特定卡片并将其显示在主页中。

我现在的问题是

  1. 当我刷新浏览器时,收藏的卡片只出现在主页中,当我使用工具栏导航时它没有显示任何内容。

  2. 当我过滤了特定的收藏卡然后将其删除时,它仍然会出现。例如,我在搜索栏中输入“食物”并出现 5 张卡片,我删除 1 张并取消我的搜索,然后删除卡片仍然出现。再次刷新浏览器后就消失了。

谁能帮我修复这个错误?

卡片组件收藏和不收藏功能

  toggleFavorite(): void {
    if (!this.card.isFavorite) {
      this.userService.addUserFavorite(this.card.type, this.card.guid, 0, 0).subscribe((res) => {
        if (res) {
          this.card.isFavorite = true;
          this.removeFromList.emit(this.card.id);
          this.refreshCardList.emit(true);
        }
      });
    } else {
      this.userService.removeFavorite(this.card.guid, this.card.type).subscribe((res) => {
        if (res) {
          this.card.isFavorite = false;
          this.refreshCardList.emit(true);
          this.removeFromList.emit(this.card.id);
        }
      });
    }

主页组件,这是我在主页中显示用户收藏卡的方式

  <div *ngIf="favorites.length > 0">
    <app-card-list [cards]="favorites"></app-card-list>
  </div>

主页组件 ts


  favorites: List<Favorite>;
  loading: boolean;
  getUserFavs$: Subject<void> = new Subject();
  searchInput: string;
  user: User;
  query: string;
  inputCtrl: FormControl = new FormControl();

  constructor(private userService: UserService, private cdr: ChangeDetectorRef) {}

  ngOnInit(): void {
    this.loading = true;
    this.getUserFavs$
      .pipe(
        switchMap(() => {
          return this.userService.getUser();
        }),
      )
      .subscribe((user: User) => {
        this.favorites = user.userFavorites;
        this.user = JSON.parse(JSON.stringify(user));
        this.loading = false;
     this.cdr.detectChanges();  // treid this but still not working
      });
    this.getUserFavs$.next();
    this.filterChanged();
     this.cdr.detectChanges();
  }

【问题讨论】:

    标签: html angular typescript eventemitter emit


    【解决方案1】:

    使用 ChangeDetectorRef... 构造函数(私人更改:ChangeDetectorRef){ }

    从服务获得响应并分配给卡变量后 使用 this.change.detectChanges()

    【讨论】:

      猜你喜欢
      • 2021-03-09
      • 2018-12-04
      • 1970-01-01
      • 1970-01-01
      • 2018-04-26
      • 2020-04-19
      • 2021-08-17
      • 1970-01-01
      • 2018-05-13
      相关资源
      最近更新 更多