Angular form submission: Redirecting to success message on a separate page

When a user submits a form on my website, they are redirected to another page where a success message is displayed.

Below is the code from the article-update.component.html file:

<form class="form-horizontal" [formGroup] = 'articleUpdateForm' (ngSubmit) = 'onSubmit()' enctype="multipart/form-data">
  <label for="articleTitle">Title</label>
    <input class="form-control" type="text" id="articleTitle" formControlName="title" [ngClass]="{ 'is-invalid': submitDisable && formValues.title.errors }" />
  <label>Description</label>
     <textarea formControlName='description' id="summernote" class="summernote"></textarea>
      <button class="btn btn-info" type="submit">Update</button>
</form>

The content of the article-update.component.ts file is as follows:

import { Component, OnInit } from '@angular/core';
   import {FormBuilder, FormControl, FormGroup, ValidatorFn, Validators} from '@angular/forms';
 
 @Component({
 selector: 'kt-article-update',
 templateUrl: './article-update.component.html',
 styleUrls: ['./article-update.component.scss']
 })
 export class ArticleUpdateComponent implements OnInit {
   // Code for the component...
 }

Answer №1

article-service.ts file

import { ApiService } from './api.service';
import { Observable } from 'rxjs';
import { BehaviorSubject } from 'rxjs';
import { Injectable } from '@angular/core';

@Injectable()
export class ArticleService {

  private _articleModified: BehaviorSubject<boolean> = new BehaviorSubject(false);
  public readonly articleModified$: Observable<boolean> = this._articleModified.asObservable();

  constructor(private apiService: ApiService) { }

  updateArticle(formData, d): Promise<any> {
    return new Promise((resolve, reject) => {
      this.apiService.post('/updateArticle', formData).subscribe((result: any) => {
        this._articleModified.next(true);
        resolve(result.status)
      }, (error) => {
        this._articleModified.next(false);
        reject(error.messages ? error.messages : error.message);
      });
    });
  }
}

article-list.component.ts file

import { Subscription } from 'rxjs';
import { ArticleService } from './../../services/article.service';
import { Component, OnInit, OnDestroy } from '@angular/core';

@Component({
  selector: 'app-article-list',
  templateUrl: './article-list.component.html',
  styleUrls: ['./article-list.component.css']
})
export class ArticleListComponent implements OnInit,OnDestroy {

  updateMessage: boolean;
  articleUpdateSubscription: Subscription;

  constructor(
    private articleService: ArticleService
  ) { }

  ngOnInit() {
    this.articleUpdateSubscription = this.articleService.articleUpdated$.subscribe(isModified => {
      this.updateMessage = isModified;
    });
  }

  ngOnDestroy(){
    if(this.articleUpdateSubscription)
      this.articleUpdateSubscription.unsubscribe();
  }
}

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

Applying the spread operator in the map function for copying objects

In my Angular application, I am attempting to copy an object and add a new property using the spread operator. To add the new property, I have created a method called 'addNewProperty(name)' which returns the property and its value. However, when ...

Utilizing a nested interface in Typescript allows for creating more complex and

My current interface is structured like this: export interface Foo { data?: Foo; bar?: boolean; } Depending on the scenario, data is used as foo.data.bar or foo.bar. However, when implementing the above interface, I encounter the error message: Prope ...

What is the best way to merge the results of several runs of an observable function

When working with Firestore, I need to retrieve multiple documents, each with a unique sourceAddressValue. This means for a list of N strings, I may need to fetch N documents. I attempted the following approach: getLocationAddresses(addresses: string[]) { ...

An error has occurred: module @angular-devkit/build-angular/package.json could not be located

Whenever I try to run my project on VS Code, which has been working fine for others, I encounter this strange error that is beyond my understanding. Here is the screenshot of the error message: https://i.sstatic.net/xUBsZ.png It seems like there might be ...

How can we incorporate an algorithmic solution into an Angular brand carousel?

I am seeking to create a brand slider in Angular without relying on any external libraries or packages. The functionality I desire is as follows: 1 2 3(active) 4 5 2 3 4(active) 5 6 3 4 5(active) 6 7 4 5 6(active) 7 (empty) 5 6 7(active) (empty) (empt ...

Upon setting up 'next-auth@beta' on the server, I encountered the [ERR_REQUIRE_ESM] Error

I have successfully integrated Next Auth into a Next Js application, which utilizes apollo client and apollo server with graphql. I have set up OAuth with Google using Next Auth v5 that supports App Router. On the frontend, I am able to handle sign-in, sig ...

Can we use a switch statement instead of having multiple @Input()s in Angular?

When passing an attribute into my Angular component like this: <my-component myAttribute></my-component> I aim to modify a variable within the component that controls the CSS properties for width and height. To simplify, I have predefined at ...

Verifying the eligibility of a value for a union type

In my app, there is a type called PiiType that enforces strong typing: type PiiType = 'name' | 'address' | 'email'; When receiving potentially sensitive information from the server, we need to verify if it aligns with this d ...

Property missing in Typescript type definition

In my Typescript Next project, I am using this component: import PageTitle from './pagetitle' import style from './contact.styl' export default function Contact() { return ( <section> <a name="contact"> ...

Communication among sub applications is crucial for the success of Micro Frontends

After researching the best practices for frontend applications, I made the decision to refactor our monolith application. Instead of choosing between micro frontends and mono repo approaches, I decided to merge them both in a unique way. I plan to create ...

Typescript: Implementing a generic function with the flexibility of an optional parameter

Having some difficulty writing a generic function with an optional parameter type Action<TParameters = undefined> = (parameters: TParameters) => void const A: Action = () => console.log('Hi :)') // This works as expected const B: ...

Autocomplete in Angular causing TypeError: Unable to access 'filter' property of undefined

I'm currently implementing Autocomplete in Angular <input type="text" matInput [ngModel]="chatList" [matAutocomplete]="autocopmlete" (focus)="filter('')" (ngModelChange)="filter($event)"&g ...

Angular 4 Filtering Pipe: Simplify Data Filtering in Angular

Attempting to replicate AngularJS's OrderBy feature. Working with an array like this, I am aiming to filter the cars by their car category. [ { "car_category": 3, "name": "Fusion", "year": "2010" }, { "car_category": 2, "na ...

Bring in all Functions and Interfaces from the Types Definition

How can I call the function below in TypeScript: nlp.text("Hi Dr. Miller the price is 4.59 for the U.C.L.A. Ph.Ds.").sentences.length // 1 To make this function call work, what would be the correct import statement needed from this types definition? It& ...

Attempting to install angular-in-memory-web-api using npm, but encountering various errors in the process

When trying to install angular-in-memory-web-api using npm, an error with code ERESOLVE occurred. The dependency tree could not be resolved, causing a conflict. While resolving dependencies for the project, it was found that @angular/common version ~13. ...

Custom date ranges in ngx-bootstrap datepicker

Is there a way to capture the event from custom date range buttons in ngx-bootstrap datepicker? I am currently using Quick select ranges feature from ngx-bootstrap (link) and would like to trigger an event specifically when these buttons are clicked. Any ...

Retrieving the latest status array by index using Typescript in Angular

Need help with this code logic. I am working on an array and function : import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.compon ...

Unraveling the mystery of nested optional indexes in interfaces

Discover the interface outlined on this TS playground export type GetTestimonialsSectionQuery = { __typename?: 'Query', testimonialsSection?: { __typename?: 'TestimonialsSection', id: string, testimonials: Array< ...

How can I enable the feature of automatic address population when entering a PIN CODE in an Angular application?

I have created an HTML file where I aim to automatically fill in the DISTRICT, STATE, and CITY fields once a user enters the PIN CODE. The data will be fetched using an API. The API link is: <div class="cardParts5"> <di ...

When attempting to upload a file using Angular HttpClient with form data and file, I encountered an issue where multer was unable to fetch

I am facing an issue while trying to upload my form data along with an image file. It seems like my HTTP request is not properly passing the file to the backend. Alternatively, there might be some issue with my multer setup as it is not able to pick up the ...