【问题标题】:Angular how to display the result of a post request in a componentAngular如何在组件中显示发布请求的结果
【发布时间】:2019-03-09 23:55:34
【问题描述】:

在我的 Angular 应用程序中,我试图在另一个组件(即确认页面)中显示发布请求的结果。我想知道什么是最好的方法。在我的组件中,代码执行了一个发布请求,该请求发布到服务器,如下所示:

import { Component, OnInit } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { FormGroup, FormControl } from '@angular/forms';
import { Validators } from '@angular/forms';
import { FormBuilder } from '@angular/forms';
import { Request } from '../../models/request.model'
import { Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AppComponent } from '../../../app.component';
import { nowService } from '../../services/now.service';
import { HttpClient, HttpEventType, HttpHeaders, HttpRequest, HttpResponse } from '@angular/common/http';




@Component({
  selector: 'app-service-request',
  templateUrl: './service-request.component.html',
  styleUrls: ['./service-request.component.scss']
})
export class ServiceRequestComponent implements OnInit {


  public loading = false;

  private customer_id = this.appComponent.customer_id;

  serviceForm;

  u_destination_country = [
    { value: 'Choose an option' },
    { value: 'United Kingdom', },
    { value: 'United States of America', },
    { value: 'Russia', },
    { value: 'Moscow', },
    { value: 'Africa', },
  ];

  users = [
    { id: 'Select an option', },
    { id: '1', },
    { id: '2', },
    { id: '3', },
  ];

  devices = [
    { id: 'Select an option', },
    { id: '1', },
    { id: '2', },
    { id: '3', },
  ];

  constructor(private service: nowService,
    private appComponent: AppComponent,
    private router: Router,
    private http: HttpClient

  ) {
  }

  ngOnInit() {
    this.serviceForm = new FormGroup({
      customer_id: new FormControl(this.customer_id),
      si_id: new FormControl('', Validators.required),
      u_destination_country: new FormControl(this.u_destination_country[0], Validators.required),
      u_short_description: new FormControl('', Validators.compose([
        Validators.required,
        Validators.minLength(5),
        Validators.maxLength(80)
      ])),
      u_message_description: new FormControl(''),
    });
  }

  onSubmit() {
    this.http.post("/api/inc",
      this.serviceForm.value,
      {
        headers: new HttpHeaders().set("Content-Type", "application/json")
      }
    ).subscribe((response: any) => {
      console.log(response);//On success response
      this.router.navigate(['/inc/confirmation']);
    }, (errorResponse: any) => {
      console.log(errorResponse); //On unsuccessful response
    });
    if(this.serviceForm.invalid) {
      this.serviceForm.setErrors({ ...this.serviceForm.errors, 'required': true });
      return;
    }
  }
}

所以我想做的是显示display_value 的值,类似于:

result: Array(1)
0:
display_name: "number"
display_value: "INC001"
status: "inserted"
table: "incident"

【问题讨论】:

  • 您可以创建一个服务,它将http.post() 作为Observable 返回。或者通过绑定到HTML 中的@Input 属性。看这里:angular.io/guide/component-interaction
  • 你有代码示例吗?
  • 你想对第二个组件中的数据做什么?你想修改它们还是只显示结果?
  • 只显示值:display_value: "INC001" 例如:INC001
  • 我又找到了一种方法,我会上传代码。

标签: javascript angular


【解决方案1】:

对于 Angular 7.2.0 及更高版本

您可以使用 Angular 路由器中内置的 NavigationExtras 来实现。为此,您只需添加两件事。

第一步:

更新 this.route.navigate(['/inc/confirmation']) 到这个

this.router.navigate(['/inc/confirmation'],{state: {response}});

第二步:

在您的第二个组件中,您可以通过将其添加到您的代码来访问state

const state = this.router.getCurrentNavigation().extras.state;
this.response = state.response;

然后就可以显示了。

对于 Angular 7 及更低版本:

第一步:

更新this.route.navigate(['/inc/confirmation']) 到这个

this.router.navigate(['/inc/confirmation'],{queryParams: {value: response.result[0].display_value}});

第二步:

在您的第二个组件中,您可以通过将其添加到您的代码来访问 state

constructor(private route: ActivatedRoute){}
 ...
this.value = this.route.snapshot.queryParamMap.get('value');

然后就可以显示了。

当您不想使用 URL 参数时:

您可以使用一个属性创建服务

@Injectable({
  providedIn: 'root'
})
export class SharedDataService {
  public sharedData;
  constructor() {
  }
}

然后你可以在重定向到另一个路由之前设置 sharedData。

constructor(private sharedService: SharedDataService){}
...
this.sharedService.sharedData = response;
this.route.navigate(['/inc/confirmation']);

您可以在第二个组件中获取该数据。

constructor(private sharedService: SharedDataService){}
...
this.response = this.sharedService.sharedData;

【讨论】:

  • 执行步骤 1 会出现此错误:Argument of type '{ state: { response: any; }; }' 不可分配给“NavigationExtras”类型的参数。对象字面量只能指定已知属性,并且“状态”不存在于“NavigationExtras”类型中。
  • 你用的是什么版本?
  • Angular 版本 6
  • 哦,这是从版本 7.2.0 开始的。我有此信息的更新答案。
  • 谢谢,但我需要版本 6 的解决方案
猜你喜欢
  • 1970-01-01
  • 2017-03-04
  • 2017-01-21
  • 1970-01-01
  • 1970-01-01
  • 2019-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多