Refreshing the page in Angular 2 without changing the route page

I am currently working on a Component that displays a list of projects, along with Edit and Delete buttons.

When the delete button is clicked:

onDelete(projectName: string): void {
    this.projectService.deleteProject(projectName);

    this.router.navigate(['/projects']);
}

Within my router component:

export const projectListRouters: Routes = [
{
    path: '',
    children: [
        {path: '', component: URLComponent},
        {path: 'login', component: Login},
        {path: 'projects', canActivate: [AuthGuard], component: ProjectListComponent},

        {path: 'project/new/-', component: ProjectDetails, canActivate: [AuthGuard], data: {oparationType: 'new'}},

        // otherwise redirect to home
        {path: '**', redirectTo: ''}
    ],
},

];

The issue I am facing is that when I use this.router.navigate(['/projects']), the list is not being refreshed after deleting a project.

Answer №1

It seems like you are redirecting to the same page. To handle this situation, make sure to update your model, such as the projectList, which contains the list of project names.

If the deleteProject function is asynchronous, then include this.router.navigate(['/projects']); within a promise. Otherwise, simply removing the element from the projectList should suffice.

I hope these suggestions are helpful for you!

Answer №2

One option is to generate a dummy component to simulate the refresh process. Redirecting to this dummy component and then back to /projects can help achieve the desired outcome.

Following the deletion of an item, triggering a call to the backend to fetch the updated list of projects is recommended. This mirrors the approach taken when initially loading the component.

Answer №3

Instead of loading your project list within the delete function, it might be better to subscribe to a service that handles this.

delete() {

        this._service.delete(this.id).
            subscribe(x=> {
                // Load the project list after deletion.
                this.projectList();
               }, error => {
                alert(error);
            });
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sign up for a variety of HTTP observables subscriptions

I have a collection of Observables stored in activatedRoute.data.example and I need to listen for the most recent value emitted. private data$ = forkJoin( this.activatedRoute.data.pipe( map(({ examples }) => examples) ) ); ngOnInit(): void { ...

What is the best way to arrange the table headers in a single row within an angular material table?

I need some help with formatting my Material table values differently: Current display format: Name | Quantity Mango | 10 <div class="table-cover center-table"> <div class="mat-elevation-z8 elevation-scroll-control"> <t ...

When using Angular, a service can be declared in the viewProviders of the parent component and then accessed in the viewProviders of the child

Imagine a scenario where there is a parent component called AppComponent, a directive named MyDirective, and a service named SimpleService. In this case, MyDirective is utilized in the template of AppComponent and injects SimpleService using the Host deco ...

Module not found: vueform.config

For my current project, I decided to integrate Vueforms into the codebase. However, when I pasted their installation code into both my .ts and .js files, I encountered errors during the import of vueformconfig and builderconfig. This is a snippet of my ma ...

Discover how to retrieve service response data from an API and populate it into the Select Option with Angular 2

Api.services.ts getListOfNames() { return this.http.get(this.BaseURL + 'welcome/getnama') .pipe(map(response => { return response; })); } After making the API call, I receive the following resp ...

Error: Attempting to access the value property of a null object within a React Form is not possible

I am currently developing a form that includes an HTML input field allowing only numbers or letters to be entered. The abbreviated version of my state interface is outlined below: interface State { location: string; startDate: Date; } To initiali ...

Tips for declaring a non-reactive instance property in Vue.js with TypeScript

I am currently in the process of transitioning my Vue.js components to TypeScript. In accordance with the recommendations provided in the documentation, I attempted to utilize Vue.extend() for my component implementation. The code snippet for my component ...

I'm facing a roadblock with installation of angular due to a permission denied

Error: Permission denied to access '/Users/gs/.npm-global/lib/node_modules/@angular/cli'', npm ERR! errno: -13, npm ERR! code: 'EACCES', npm ERR! syscall: 'access', npm ERR! path: npm ERR! '/Users/gs/.npm- ...

TypeScript Compile Error: The property is not available in the 'IStateParamsService' type

My client project heavily utilizes TypeScript. Currently, I am encountering a technical issue. Within my HTML code, I have an anchor tag as shown below: <a class="btn btn-default mrm" ui-sref="course-detail({courseId: '{{c.Id}}'})">Detail ...

Testing Angular 2 sending headers through service with Http module: A step-by-step guide

Is there a method to confirm and test the headers being sent when assessing an Angular 2 service that executes http requests such as GET, POST, PUT, etc.? ...

Assign an appropriate label to this sonarqube input field

Sonarqube flagged an issue with the following line of code: <div class="dropdown-language"> <label>{{'GENERALE.LINGUA' | translate }}</label> <select #langSelect (change)="translate.use(langSe ...

What sets apart the browser's debugger from Angular's setTimeout function?

I'm currently working on an angular application that is embedded within a larger application that I do not have access to. I am using a router to navigate between pages after a pop-up modal has been acknowledged (checkbox & button). It's crucial ...

Is there a way to deactivate or hide a button in Angular 9 when the user navigates from the current page to the previous one?

ABC page has both a "Back" and "Next" button. After clicking the "Next" button, I am directed to the XYZ page, which also includes a "Back" button. When I click the "Back" button on the XYZ page, I should be brought back to the ABC page without seeing th ...

Is it possible for a voiceover artist to initiate API requests?

As I work on the registration feature of my application, I am faced with the requirement that email addresses must be unique in the database. Since I am responsible for the front-end development, I am considering creating a Value Object (VO) that can make ...

Is there a way to dynamically adjust the size of an image in NodeJS utilizing Sharp, when only provided with a URL, employing async/await, and ensuring no local duplicate is

In my current work environment, the only image processing library available is NodeJS's Sharp for scaling images. It has been reliable due to its pipe-based nature, but now I have been given the task of converting it to TypeScript and utilizing Async/ ...

Steps for incorporating a new element in Reactjs

While attempting to insert a new element into a React object, I encountered the following issue: const isAdmin = true let schema = { fname: Yup.string().required('Required'), lname: Yup.string().required('Required&apo ...

Setting up a project with Angular 2 and NodeJS

Hello there, I have some inquiries about organizing the project structure of a MEAN application with Angular2. Initially, I followed the introductory guide on angular.io to create a basic Angular2 app. Now, I am attempting to incorporate this app into a N ...

Error message: Angular Universal running on Docker encountered an HTTP failure response from an unidentified URL

My current setup consists of the following: I have four services defined in my docker-compose.yml file: my_nginx, my_client, my_api, and my_db. Using my_nginx as a proxy pass to access my_client:8000 and my_api:8001, both running on Node.js. The my_clie ...

The name 'Diagnostics' cannot be located

I've downloaded the Typescript repository and am currently reviewing the code. However, I keep encountering this recurring error message: Cannot find name 'Diagnostics' This error pops up on lines that are similar to this: Diagnostics._ ...

Error encountered in typescript when trying to implement the Material UI theme.palette.type

Just starting out with Material UI and TypeScript, any tips for a newcomer like me? P.S. I'm sorry if my question formatting isn't quite right, this is my first time on Stack Overflow. https://i.stack.imgur.com/CIOEl.jpg https://i.stack.imgur.co ...