我创建了成功警报,该警报在成功编辑或删除帖子后显示,但是存在一个问题。当我执行操作时,单击“后退”按钮并打开另一条帖子,直到我单击“ X”关闭按钮,警报消息仍保持显示。 我知道可以通过单击“后退”后更改警报状态来解决,但我想知道是否有更好的解决方案。例如,创建一个可观察对象以显示警报,然后在每个功能结束时取消订阅。您如何看待,我该如何解决?
这是我的component.ts文件:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { FormService } from './forms.service';
import { HttpClient } from '@angular/common/http';
import { alert } from './alert';
@Component({
selector: 'app-forms',
templateUrl: './forms.component.html',
styleUrls: ['./forms.component.css']
})
export class FormsComponent implements OnInit {
alert: alert;
id: any;
posts: any;
constructor(public formService: FormService ,private route: ActivatedRoute,
private router: Router, private http: HttpClient) { }
ngOnInit() {
this.id=this.route.snapshot.params['id'];
this.alert = new alert();
this.posts = this.formService.getForms(this.id).subscribe(
(forms: any) => {
this.formService.form = forms[0];
}
);
}
editPost() {
this.formService.editForm()
.then((res:any) => {
this.formService.alert.setAlert("Post has been successfully saved !");
})
}
deletePost() {
this.formService.deleteForm()
.subscribe(
data => {
console.log("DELETE Request is successful ", data);
this.formService.alert.setAlert("Post has been successfully deleted !");
},
error => {
console.log("Error", error);
}
)
}
}
这是我的service.ts文件:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { form } from './form-interface';
import { alert } from './alert';
@Injectable({
providedIn: 'root'
})
export class FormService {
formsUrl = "https://jsonplaceholder.typicode.com/posts";
form: form = {
id: 0,
userId: 0,
title: '',
body: ''
};
alert: alert;
constructor(private http: HttpClient) {
this.alert = new alert();
}
getForms(id) {
return this.http.get('https://jsonplaceholder.typicode.com/posts'
+ "?id=" + id)
}
editForm() {
return fetch(this.formsUrl + "/" + this.form.id, {
method: 'PUT',
body: JSON.stringify(this.form),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then(response => response.json())
}
deleteForm() {
return this.http.delete(this.formsUrl + "/" + this.form.id);
}
}
这是我的alert.ts文件:
export class alert{
"status" : boolean;
"text": string;
constructor(){
this.status=false;
this.text="";
}
public setAlert(text){
this.status = true;
this.text = text;
}
public close(){
this.status = false;
}
}
这是我的html文件:
<div class="container">
<a class="btn btn-primary pull-right" routerLink = '/posts' >
Back
</a>
</div>
<div class="container">
<h2>Edit:</h2>
</div>
<div class="forms container">
<form #postForm="ngForm">
<div class="form-group">
<label for="title">Title</label>
<input [(ngModel)]="formService.form.title"
name="title"
id="title"
type="text"
class="form-control"
>
</div>
<div class="form-group">
<label for="body">Body</label>
<textarea [(ngModel)]="formService.form.body"
name= "body"
id="body"
cols="30"
rows="10"
class="form-control"
></textarea>
</div>
<button class="btn btn-success" (click) = "editPost()">Save</button>
<button class="btn btn-danger pull-right" (click) = "deletePost()">Delete</button>
<div class="container mt-4">
<div class="row">
<div class="col">
<div *ngIf = "formService.alert.status" class="alert alert-success
alert-dismissible fade show" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"
(click) = "formService.alert.close()">
<span aria-hidden="true">×</span>
</button>
{{formService.alert.text}}
</div>
</div>
</div>
</div>
</form>
</div>
答案 0 :(得分:0)
如果您想在每次单击某个位置时擦拭警报对话框,建议您在click
上添加一个可观察对象来监听document
事件。不要忘记在类构造函数中注入ElementRef
,并为takeWhile
,Subscription
,BehaviorSubject
和Observable
正确导入。关于您的rxjs版本,您可能需要使用pipe
。
private alertOpened$ = new BehaviorSubject(false); // your alert is closed by default
private isOpenedSubscription: Subscription;
private clickSubscription: Subscription;
private isAlive = true; // auto unsubscribe
public ngOnInit() {
this.isOpenedSubsscription = this.alertOpened$
.takeWhile(() => this.isAlive)
.subscribe((isAlertOpened) => {
if (!isAlertOpened && this.clickSubscription) {
this.clickSubscription.unsubscribe();
}
this.clickSubscription = Observable.fromEvent(document, 'click')
.takeWhile(() => this.isAlive)
.subscribe((event: MouseEvent) => {
if (!this.elemRef.nativeElement.contains(event.target)) {
this.formService.setAlert(null);
this.alertOpened$.next(false);
}
});
});
}
public ngOnDestroy() {
this.isAlive = false;
}
editPost() {
this.formService.editForm()
.then((res:any) => {
this.alertOpened$.next(true);
this.formService.alert.setAlert("Post has been successfully saved !");
})
}