forked from realworld-apps/angular-realworld-example-app
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfavorite-button.component.ts
More file actions
74 lines (68 loc) · 1.93 KB
/
favorite-button.component.ts
File metadata and controls
74 lines (68 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import {
Component,
DestroyRef,
EventEmitter,
inject,
Input,
Output,
} from "@angular/core";
import { Router } from "@angular/router";
import { EMPTY, switchMap } from "rxjs";
import { NgClass } from "@angular/common";
import { ArticlesService } from "../services/articles.service";
import { UserService } from "../../../core/auth/services/user.service";
import { Article } from "../models/article.model";
import { takeUntilDestroyed } from "@angular/core/rxjs-interop";
@Component({
selector: "app-favorite-button",
template: `
<button
class="btn btn-sm"
[ngClass]="{
disabled: isSubmitting,
'btn-outline-primary': !article.favorited,
'btn-primary': article.favorited,
}"
(click)="toggleFavorite()"
>
<i class="ion-heart"></i> <ng-content></ng-content>
</button>
`,
imports: [NgClass],
})
export class FavoriteButtonComponent {
destroyRef = inject(DestroyRef);
isSubmitting = false;
@Input() article!: Article;
@Output() toggle = new EventEmitter<boolean>();
constructor(
private readonly articleService: ArticlesService,
private readonly router: Router,
private readonly userService: UserService,
) {}
toggleFavorite(): void {
this.isSubmitting = true;
this.userService.isAuthenticated
.pipe(
switchMap((authenticated) => {
if (!authenticated) {
void this.router.navigate(["/register"]);
return EMPTY;
}
if (!this.article.favorited) {
return this.articleService.favorite(this.article.slug);
} else {
return this.articleService.unfavorite(this.article.slug);
}
}),
takeUntilDestroyed(this.destroyRef),
)
.subscribe({
next: () => {
// this.isSubmitting = false;
// this.toggle.emit(!this.article.favorited);
},
error: () => (this.isSubmitting = false),
});
}
}