简体   繁体   English

使用 BehaviorSubject 或 Subject 更新 Angular 组件无法正常工作

[英]update Angular component with BehaviorSubject or Subject don't work correctly

everybody, I have an angular 14 app and I have a service called UserService and a component called UserListComponent and in the service i create a function to get data from API and send it to Component with BehaviorSubject.大家好,我有一个 Angular 14 应用程序,我有一个名为 UserService 的服务和一个名为 UserListComponent 的组件,在该服务中我创建了一个函数来从 API 获取数据并将其发送到具有 BehaviorSubject 的组件。

This is user.service.ts这是 user.service.ts

// userChanged = new BehaviorSubject<UserDto[]>([]);

userChanged = new BehaviorSubject<any>(null);

constructor(private httpClient: HttpClient) {
}

getAll(): void {
  this.httpClient.get<UserDto[]>(`${this.BASEURL}/user`).subscribe({
    next: (res: UserDto[]) => {
      console.log('next data');
      console.log(res);
      this.userChanged.next(res);
    },
    error: err => console.log(err)
  });
}

` `

this is user-list.component.ts这是 user-list.component.ts

export class UserListComponent implements OnInit, OnDestroy {
  users: UserDto[] = [];
  loading: boolean = false;
  userSubscription: Subscription;

  constructor(private userService: UserService) {
  }

  ngOnInit(): void {
    this.getAllUsers();
  }

  loadData() {
    this.userService.getAll();
  }

  getAllUsers() {
    this.loading = true;
    this.userSubscription = this.userService.userChanged.subscribe({
      next: res => {
        console.log('users received----------------------------------------------');
        console.log(res);
        this.users = res;
        console.log(this.users);
        this.loading = !res;
      },
      error: err => console.error(err),
      complete: () => console.log('complete')
    });
  }

  ngOnDestroy(): void {
    this.userSubscription.unsubscribe();
  }

}

this is user-list.component.html这是 user-list.component.html

 <button (click)="loadData()">load data</button>
<tr *ngFor="let user of users">
          <td>
            <div class="form-check form-check-sm form-check-custom form-check-solid">
              <input class="form-check-input widget-9-check" type="checkbox" value="1"/>
            </div>
          </td>
          <td>
            <span class="text-dark d-block mb-1 fs-7" href="#">{{user.firstName}} {{user.lastName}}</span>
          </td>
          <td>
            <span class="text-dark d-block mb-1 fs-7" href="#">{{user.userName}}</span>
          </td>
          <td>
            <a class="text-dark text-hover-primary d-block mb-1 fs-7" href="#">{{user.email}}</a>
          </td>
          <td>
            <a class="text-dark  text-hover-primary d-block mb-1 fs-7" href="#">
              {{user.isActive}}
            </a>
          </td>
          <td class="text-end">
            <a class="btn btn-icon btn-bg-light btn-active-color-primary btn-sm me-1" href="#">
              <i class="fa-solid fa-shield-halved"></i>
            </a>
            <a class="btn btn-icon btn-bg-light btn-active-color-primary btn-sm me-1" href="#">
              <i class="fa-solid fa-pencil"></i>
            </a>
            <a class="btn btn-icon btn-bg-light btn-active-color-primary btn-sm" href="#">
              <i class="fa-solid fa-pencil"></i>
            </a>
          </td>
        </tr>

in oninit i subscribe my BehaviorSubject and when i click load data i get data from api and send data with BehaviorSubject,but don't work correctly and when click load data button again(twice) dat is loaded.在 oninit 中,我订阅了我的 BehaviorSubject,当我单击加载数据时,我从 api 获取数据并使用 BehaviorSubject 发送数据,但无法正常工作,当再次(两次)单击加载数据按钮时,dat 被加载。 i don't want to use resolver.我不想使用解析器。 thank u.感谢你。

i expect to know why i click twice load data button to load data and what is my wrong?我想知道为什么我点击两次加载数据按钮来加载数据,我的错误是什么?

For simple answer: I think you should add your loadData method to ngOnInit.对于简单的回答:我认为你应该将你的 loadData 方法添加到 ngOnInit。 Because it's the actual method which brings the users that you want.因为这是带来您想要的用户的实际方法。 However, I have some recommendations for you.不过,我有一些建议给你。

  • Don't subscribe inside your service, use your components instead (definitely you can do further research about it)不要在你的服务中订阅,而是使用你的组件(当然你可以做进一步的研究)
  • delete getAllUsers method and in loadData add subscribe method after getAll() and inside the subscribe assign all your users.删除 getAllUsers 方法并在 loadData 中添加 subscribe 方法,在 getAll() 之后并在 subscribe 中分配所有用户。
  • If you would like to cache your users or somehow want to store them in your service you can still keep them in your service as well.如果您想缓存您的用户或以某种方式想将它们存储在您的服务中,您仍然可以将它们保留在您的服务中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 服务中的Angular 2和rxjs主题未在组件上更新 - Angular 2 and rxjs subject in service isn't being update on component Angular BehaviorSubject; “下一个”方法不起作用 - Angular BehaviorSubject; the “next” method doesn't work Angular 7:更新和删除功能不起作用 - Angular 7: Update and Delete functions don't work Angular 中的主题 vs 行为主题 vs ReplaySubject - Subject vs BehaviorSubject vs ReplaySubject in Angular 角度4:主题或BehaviorSubject的自定义errorHandler不起作用 - Angular 4: Custom errorHandler with Subject Or BehaviorSubject not working 从 Angular 组件中的 BehaviorSubject 获取值 - getValue from BehaviorSubject in Angular component ANGULAR - 在组件中订阅不更新服务的值 - ANGULAR - Subscribe in component don't update value from service 角。 来自另一个组件更新模型的组件的调用方法,但不要更新被调用组件的视图 - Angular. Calling method of component from another component update model, but don't update the view of called component Angular6:自定义组件上的输入绑定无法正确更新 - Angular6: Input binding on custom component doesn't update correctly 服务和组件之间的数据链接:Subject 和 BehaviorSubject - 需要解释 - Data link between service and component: Subject and BehaviorSubject - Need explanation
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM