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.
This is 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
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
<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. 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. Because it's the actual method which brings the users that you want. However, I have some recommendations for you.