首页 > 解决方案 > 表单以角度提交后,另一个页面中的成功消息

问题描述

我有表单,当用户提交表单时,用户将被重定向到另一个我想显示成功消息的页面。

这是 article-update.component.html 文件

        <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>

文章-update.component.ts 文件

  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 {
     articleUpdateForm: FormGroup;
       submitDisable = false;
       updateMessage:boolean = false;
       id:any;
       constructor(  public fb: FormBuilder, private route: ActivatedRoute, private _router:Router) {
         this.articleUpdateForm = this.fb.group({
    title: [''],
          description: ['']
       });
        }

        ngOnInit() {
this.id = this.route.snapshot.paramMap.get('id');
}

   onSubmit() {
this.submitDisable = true;
if (this.articleUpdateForm.invalid) {

  return;
}

const formData: any = new FormData();

formData.append('title', this.articleUpdateForm.get('title').value);

formData.append('description', this.contents);


this.articleService.updateArticle(formData, this.id).subscribe(
  (response) => console.log(response),
  (error) => console.log(error),

  () => { this._router.navigateByUrl('admin/article/list'),
        this.updateMessage = true;
   }

);
  }

 }

用户更新文章后,他将被重定向到我想显示成功消息的文章列表页面,因为我已经updateMessage在 article-update.ts 文件中声明了一个变量,该变量最初是false,但当表单成功提交时,updateMessage它将变为true. article-list 是 article-update 文件的父级。

文章列表.component.html 文件

     <h1 *ngIf = 'updateMessage'> Article Updated successfully </h1>\

文章列表.component.ts 文件

           import {Component, Input, OnInit} from '@angular/core';
      @Component({
    selector: 'app-article-table',
   templateUrl: './article-table.component.html',
  styleUrls: ['./article-table.component.scss']
  })
 export class ArticleTableComponent implements OnInit {

  articles: AppModule[];
   catname : '';

   @Input() updateMessage: boolean;

   constructor() { }
    ngOnInit() {}
   }

标签: angulartypescriptlogic

解决方案


article.service.ts 文件

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

@Injectable()
export class ArticleService {

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

  constructor(private apiService: ApiService) { }

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

article-table.component.ts 文件

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

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

  updateMessage: boolean;
  articalUpdateSubscription: Subscription;

  constructor(
    private articleService: ArticleService
  ) { }

  ngOnInit() {
    this.articalUpdateSubscription = this.articleService.articleUpdated$.subscribe(isUpdated => {
      this.updateMessage = isUpdated;
    });
  }

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

推荐阅读