Angular Mat-Dialog,提交时刷新页面,而不是密切的对话框
我是Angular的新手(这里的Junior),并且在工作中的一项任务中,我必须从数据库中获取数据才能填充用户网格。我设法做到了,下一步是使用Matdialog,并在创建新用户按钮中链接。
我修复了创建服务并将其与.NET控制器链接在一起,因此现在我必须使组件刷新网格中的用户数据,以便新用户出现。
尝试了这样的解决方案: How to refresh component Matdialog关闭并在Angular 6中的数据库中更新数据
?
不过,我有一个错误,现在,当我打开对话框以填充新用户信息的字段时,即使我点击“取消”按钮,页面将像新用户提交事件调用时一样重新加载。
只有在调用提交按钮事件(NEWUSER)和对话框关闭时而不是用户点击“取消”按钮时,如何使页面刷新如何刷新?
这是对话框的打开对话框,并提交和取消方法:
1)用户网格组件添加订阅以重新加载页面
onAddUser() {
const dialogRef = this.dialog.open(AddUserRoleDialogComponent, {
width: '500px',
data: ''
}).afterClosed().subscribe(result => {
this.getUsers().subscribe((data) => {
this.users = data;
console.log(data, 'data after refresh');
console.log(this.users, 'users');
this.dataSource = data;
})
});
}
2)对话框中的newuser方法来调用API并创建用户
newUser(model: any) {
return this.http.post<any>(url, model).subscribe({
error: error => {
this.errorMessage = error.message;
console.error('There was an error!', error);
}
});
}
3)对话框取消方法,哪个方法仍然刷新页面
cancelSave(): void {
this.dialogRef.close();
}
I'm new to angular (junior here) and in one of my tasks at work, had to fetch data from the database to fill the user grid. I managed to do that and the next step was to use the MatDialog, linked in a create new user button.
I fixed the creation services and linked it with the .NET controller, so now I had to make the component refresh the user data in grid so the new user would appear.
Tried some solutions like this one:
How to refresh component after MatDialog close and data updated in database in Angular 6?
But I was unable to get anywhere, so I tried to use the window.location.reload() to achieve page reload and the new records start to appear.
I got a bug though, now when I open up the dialog to fill the fields of the new user information even if I hit the cancel button the page will be reloaded like when the new user submit event call.
Any suggestions on how to make the page refresh only when the submit button event is called (newUser) and the dialog closes and not when the user hit the cancel button?
Here is the open dialog with subscribe and the submit and cancel methods of the dialog:
1)User grid component with subscribe in order to reload the page
onAddUser() {
const dialogRef = this.dialog.open(AddUserRoleDialogComponent, {
width: '500px',
data: ''
}).afterClosed().subscribe(result => {
this.getUsers().subscribe((data) => {
this.users = data;
console.log(data, 'data after refresh');
console.log(this.users, 'users');
this.dataSource = data;
})
});
}
2)newUser method in dialog to call the api and create the user
newUser(model: any) {
return this.http.post<any>(url, model).subscribe({
error: error => {
this.errorMessage = error.message;
console.error('There was an error!', error);
}
});
}
3)Dialog cancel method which still refreshes the page
cancelSave(): void {
this.dialogRef.close();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将各种评论汇总到一个(希望)的答案中:
根据评论,强迫用户重新加载的最后一项是最后一次度假胜地。
理想情况下,在这样的情况下,您只需更新数据客户端(您知道自己创建/更新/删除的内容,以便您可以影响自己的改变)。
可悲的是,这通常是较大的工作。
接下来是继续,然后再次提出API请求。非常简单,我个人最喜欢的是,因为它很快,并且取决于我的工作,“足够好”。
只有作为最后的手段,您才能完全刷新页面。通常,没有必要。您的页面应由您可以将新数据推向的单个组件组成,或者告诉您重新提取数据。很少有您需要刷新的情况。
解决第1期的问题 - 即使在关闭时,持续的力量重新加载:
每评论,这是一种告诉您的组件,当它关闭时是否应该重新加载。这是用
this.dialogref.close()
方法完成的。你可以给它一些东西!例如,一个布尔来决定是否应该重新加载...因此,在关闭时:
对于第2期,重新加载本身:
不是重新加载窗口...
而不是进行窗口重新加载,而是再次进行API请求,而 - 角变化检测:
这实际上取决于您用来显示数据的内容。大多数事情可能只是添加到阵列的情况下 - 在引擎盖下是某种形式的循环。这只是他们检查什么以及检查的频率。
总体而言,Angular不会注意到属性更改(即如果对象具有“名称”属性,并且您更改了名称,则Angular不一定会对它做出反应)。
Angular会反应的是整体变化的对象。较新的ES语言功能提供了一个不错的简化传播操作员,以帮助创建“新”对象,可在对象和数组中触发更改,例如:
例如,如果
somebobject
是>输入
对组件,该组件将在第二个实例中触发其更改检测,而不是第一个。数组 -
this.somearray = [... this.somearray]
也是如此。编辑:
您需要进行这些更改,因为您如何将新用户请求连接起来。
通常,您将返回可观察的(
this.http.get/post/etc/etc(...)
),然后任何想提出该请求的内容都将.subscribe(...)< /代码>对此。是
.subscribe()
实际上可以做到这一点。取而代之的是,您拥有的是您的方法执行帖子,并立即订阅自己以获得自己的响应。您要返回的是这种订阅,而不是您想要的响应的实际价值。
作为标准,我将此机制用于所有请求,它可以使事情异步而没有任何阻塞(使用承诺和异步/等待可观察到可观察到的东西是我不会进入的)。
一项典型的服务(我创建了一个基类来包装并以几行处理所有此类内容)看起来像这样,为您的观看乐趣而扩展:
任何关心的组件都可以设置订阅为此,每当新数据进来时(任何东西都会使
getMyDataPlease()
调用),他们会获取数据。请注意,这是单火请求,执行请求,订阅,然后清除订阅(您的99%的请求可能是这样)。显然,如果您想保留一个开放的频道,则需要以不同的方式安排它,但是大多数时候,您都希望发送一个请求并收回单个响应。
ngoninit
- 设置自己准备好并收听响应,然后告诉它获取数据。ngondestroy
- 不要忘记在自己之后清理。一个小笔记,而不是我缺乏异步/等待使用的待遇:异步/等待块。
通常,您在页面上有任何设置或您想在
ngoninit
方法中都有任何要做的设置或其他操作,并且可以从多个来源获取数据。如果您全部使用了标准的async/等待方法,那么所有这些设置都将依次发生。异步/等待!=并发。
异步/等待 aids 通过(可能)释放当前线程繁忙的(可能)释放用于使用的资源,但是该程序执行会在该行上积极停止,并且直到该方法/请求/任何内容都不会继续已经完成。
有了可观察的东西,这是一场火,忘记了,继续下一行代码并继续生活。一旦响应被广播,它就会得到适当处理 - 但是您的其余代码已经完成了它的工作,而不会被阻止。
只要您对基于事件的系统感到满意,并且确保您始终正确地将其连接起来(一致性是关键!),您就不会出错。
Rolling up the various comments into a single (hopefully) answer for you:
Per the comments, forcing a window reload on users should be a last last last resort.
Ideally, in scenarios such as this, you simply update the data client side (you know what you've created/updated/deleted so you can affect that change yourself).
This is typically the larger piece of work, sadly.
Next up is to go ahead and just make the API request again. Pretty simple, my personal favourite go-to because it's quick and, depending on what I'm working on, is 'good enough'.
Only as a last resort would you completely refresh the page. In general there's no need to. Your page(s) should be made up of individual components that you can push new data to, or tell to go re-fetch data. There's very few cases when you need to do a refresh.
Tackling issue number 1 - the continued force reload even on closing:
Per comments, this is a case of telling your component whether it should or shouldn't reload when it's closed. This is done with the
this.dialogRef.close()
method. You can give it something! E.g. a bool to decide if it should reload...So when closing:
For issue #2, the reloading itself:
Instead of doing a window reload, do your API request again instead of reloading the window...
And for the third item - Angular change detection:
This actually depends on what you're using to display your data. The majority of things are probably fine just adding to the array - under the hood they're some form of loop. It's just a matter of what they check and how often they check it.
Angular, in general, won't notice property changes (i.e. if an object has a 'name' property and you change the name, Angular won't necessarily react to it).
What Angular WILL react to, is objects as a whole changing. The newer ES language features provide a nice simplified spread operator to help create 'new' objects that work well for triggering changes, for both objects and arrays:
If, for example, that
someObject
was aninput
to a component, the component would have its change detection triggered in the second instance, but not the first.Same is true with arrays -
this.someArray = [...this.someArray]
.Edit:
You needed to make those changes because of how you have your new user request hooked up.
Normally, you would return the observable (
this.http.get/post/etc(...)
) and then whatever wants to make that request would.subscribe(...)
to it. It's the.subscribe()
that makes it actually do the thing.Instead, what you have is your method doing the post, and immediately subscribing itself to get its own response. It's this subscription that you're returning, not the actual value of the response that you want.
As a standard, I use this mechanism for all my requests, it keeps things asynchronous without any blocking (using promises and async/await vs observables is a whole thing that I won't get in to).
A typical service (which I have created a base class to wrap things up and handle all this kind of stuff in a couple of lines) would look like this, expanded out for your viewing pleasure:
And any component that cares can set up a subscription to it so that whenever new data comes in (anything makes a
getMyDataPlease()
call), they get the data.Note that it's a single-fire request, doing the request, subscribing, and then clearing the subscription (99% of your requests are likely to be such). Obviously, if you wanted to keep an open channel you'd need to arrange it differently, but most of the time you'll want to be sending a single request and getting a single response back.
ngOnInit
- set yourself ready and listening to responses, then tell it to go fetch data.ngOnDestroy
- don't forget to clean up after yourself.A minor note, rather than a treatsie on my lack of async/await usage: async/await blocks.
Often, there is any amount of setup or whatnot that you want to do on a page, quite possibly in the
ngOnInit
method, as well as getting data from possibly multiple sources. If you used the standard async/await method for it all, all of that setup would happen sequentially.async/await != concurrency.
async/await aids concurrency by (possibly) freeing up resources to be used whilst the current thread is busy, but the program execution actively stops on that line and doesn't continue until that method/request/whatever has completed.
With observables, it's a fire and forget, continuing with the next line of code and getting on with life. Once the response has been broadcast, it gets handled appropriately - but the rest of your code has already done its thing without being blocked.
So long as you're comfortable with an event-based system, and you ensure you always hook it up properly (consistency is key!), you can't go wrong.