简体   繁体   English

使用 angular 和 Typescript 从 UI 传递标头的最佳方法是什么?

[英]What is the best way to pass Headers from UI using angular and Typescript?

Im getting this authorization rejection error while submitting the "save customer" form from UI-angular and typescript我在从 UI-angular 和 typescript 提交“保存客户”表单时收到此授权拒绝错误

I have created a decent form using angular and typescript. I have backend code ready.我使用 angular 和 typescript 创建了一个像样的表单。我已经准备好后端代码。 Now I have to submit this form from " http://localhost:4200/savecust ", after clicking on the submit button..I'm getting Authorization rejection error because I have not added code in angular which can actually help to pass required headers.现在我必须从“ http://localhost:4200/savecust ”提交此表单,点击提交按钮后..我收到授权拒绝错误,因为我没有在 angular 添加代码,这实际上可以帮助通过要求标题。 I would be thankful if someone helped me to know what code can be added to accept headers in angular ts.如果有人帮助我知道可以添加哪些代码来接受 angular 中的标头,我将不胜感激。

savecust.component.html savecust.component.html

<div class="container-fluid">
    <div class="container">
        <div class="row">
            <div class="col-md-6">
                <div class="card">
                    <div class="box">
                        <div class="text-center mb-4">
                            <h1>Save Customer</h1>
                            <h6>Please enter all the customer details!!</h6>
                        </div>
                        <form [formGroup]="saveCustomerForm">
                            <div class="form-group">
                                <label for="Name">Name:</label><br>
                                <input formControlName="name" type="text" class="form-control" id="name"
                                    placeholder="Name" pattern="">
                                <div *ngIf="name?.invalid && name?.touched">
                                    <span class="text-danger" *ngIf="name?.errors?.['required']">*Name is
                                        required</span>
                                    <span class="text-danger" *ngIf="name?.errors?.['pattern']">*Name should be
                                        valid</span>
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="Email">Email:</label><br>
                                <input formControlName="email" type="text" class="form-control" id="email"
                                    placeholder="Email" pattern="">
                                <div *ngIf="email?.invalid && email?.touched">
                                    <span class="text-danger" *ngIf="email?.errors?.['required']">*Email is
                                        required</span>
                                    <span class="text-danger" *ngIf="email?.errors?.['pattern']">*Email should be
                                        valid</span>
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="phone">Contact Number</label><br>
                                <input formControlName="phone" type="text" class="form-control" id="phone"
                                    placeholder="Mobile Number" pattern="^((\\+91-?)|0)?[0-9]{10}$" minLength="10"
                                    maxLength="10">
                                <div *ngIf="phone?.invalid && phone?.touched">
                                    <span class="text-danger" *ngIf="phone?.errors?.['required']">*Mobile number is
                                        required</span>
                                    <span class="text-danger" *ngIf="phone?.errors?.['minLength']">*Mobile number
                                        minimum length is ten</span>
                                    <span class="text-danger" *ngIf="phone?.errors?.['maxLength']">*Mobile number
                                        maximum length is ten</span>
                                    <span class="text-danger" *ngIf="phone?.errors?.['pattern']">*Mobile number should
                                        be valid</span>
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="Address">Address:</label><br>
                                <input formControlName="addressLine1" type="text" class="form-control" id="addressline1"
                                    placeholder="Address Line1" pattern="">
                                <div *ngIf="addressLine1?.invalid && addressLine1?.touched">
                                    <span class="text-danger" *ngIf="addressLine1?.errors?.['required']">*Address Line1
                                        is
                                        required</span>
                                    <span class="text-danger" *ngIf="addressLine1?.errors?.['pattern']">*Address Line1
                                        should be
                                        valid</span>
                                </div>

                                <!-- <input formControlName="addressLine2" type="text" class="form-control" id="addressline2"
                                    placeholder="Address Line2" pattern=""> -->
                                <!-- <div *ngIf="addressLine2?.invalid && addressLine2?.touched">
                                    <span class="text-danger" *ngIf="addressLine2?.errors?.['required']">*Address Line2
                                        is
                                        required</span>
                                    <span class="text-danger" *ngIf="addressLine2?.errors?.['pattern']">*Address Line2
                                        should be
                                        valid</span>
                                </div> -->

                                <!-- <input formControlName="addressCity" type="text" class="form-control" id="addresscity"
                                    placeholder="Address City" pattern=""> -->
                                <!-- <div *ngIf="addressCity?.invalid && addressCity?.touched">
                                    <span class="text-danger" *ngIf="addressCity?.errors?.['required']">*Address City is
                                        required</span>
                                    <span class="text-danger" *ngIf="addressCity?.errors?.['pattern']">*Address City
                                        should be
                                        valid</span>
                                </div> --><br>

                                <input formControlName="addressState" type="text" class="form-control" id="addressstate"
                                    placeholder="Address State" pattern="">
                                <div *ngIf="addressState?.invalid && addressState?.touched">
                                    <span class="text-danger" *ngIf="addressState?.errors?.['required']">*Address State
                                        is
                                        required</span>
                                    <span class="text-danger" *ngIf="addressState?.errors?.['pattern']">*Address State
                                        should be
                                        valid</span>
                                </div><br>

                                <input formControlName="addressCountry" type="text" class="form-control"
                                    id="addresscountry" placeholder="Address Country" pattern="">
                                <div *ngIf="addressCountry?.invalid && addressCountry?.touched">
                                    <span class="text-danger" *ngIf="addressCountry?.errors?.['required']">*Address
                                        Country is
                                        required</span>
                                    <span class="text-danger" *ngIf="addressCountry?.errors?.['pattern']">*Address
                                        Country should be
                                        valid</span>
                                </div><br>

                                <input formControlName="addressZip1" type="text" class="form-control" id="addresszip1"
                                    placeholder="Address Zip1" pattern="">
                                <div *ngIf="addressZip1?.invalid && addressZip1?.touched">
                                    <span class="text-danger" *ngIf="addressZip1?.errors?.['required']">*Address Zip1 is
                                        required</span>
                                    <span class="text-danger" *ngIf="addressZip1?.errors?.['pattern']">*Address Zip1
                                        should be
                                        valid</span>
                                </div>

                                <!-- <input formControlName="addressZip2" type="text" class="form-control" id="addresszip2"
                                    placeholder="Address Zip2" pattern=""> -->
                                <!-- <div *ngIf="addressZip2?.invalid && addressZip2?.touched">
                                    <span class="text-danger" *ngIf="addressZip2?.errors?.['required']">*Address Zip2 is
                                        required</span>
                                    <span class="text-danger" *ngIf="addressZip2?.errors?.['pattern']">*Address Zip2
                                        should be
                                        valid</span>
                                </div> --><br>
                            </div>

                            <div class="form-group">
                                <label for="SSN">SSN</label><br>
                                <input formControlName="ssn" type="text" class="form-control" id="ssn" placeholder="SSN"
                                    pattern="">
                                <div *ngIf="ssn?.invalid && ssn?.touched">
                                    <span class="text-danger" *ngIf="ssn?.errors?.['required']">*SSN is
                                        required</span>
                                    <span class="text-danger" *ngIf="ssn?.errors?.['pattern']">*SSN should
                                        be valid</span>
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="Customer Reference">Customer Reference:</label><br>
                                <input formControlName="customerReference" type="text" class="form-control"
                                    id="customerreference" placeholder="Customer Reference" pattern="">
                                <div *ngIf="customerReference?.invalid && customerReference?.touched">
                                    <span class="text-danger" *ngIf="customerReference?.errors?.['required']">*Customer
                                        Reference is
                                        required</span>
                                    <span class="text-danger" *ngIf="customerReference?.errors?.['pattern']">*Customer
                                        Reference should
                                        be valid</span>
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="Status">Status:</label><br>
                                <select type="button" formControlName="selectStatus" class="form-control">
                                    <option disabled selected value>....   ....  Select Status  ....   ....</option>
                                    <option *ngFor="let selectStatus of statusList">{{selectStatus}}</option>
                                </select>
                                <div class="error-block" *ngIf="handleError('selectStatus', 'required')">
                                    You must provide status type!
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="Bank Accounts">Bank Accounts:</label><br>
                                <input formControlName="nameOnAccount" type="text" class="form-control"
                                    id="nameonaccount" placeholder="Name on Account" pattern="">
                                <div *ngIf="nameOnAccount?.invalid && nameOnAccount?.touched">
                                    <span class="text-danger" *ngIf="nameOnAccount?.errors?.['required']">*Name on Account is
                                        required</span>
                                    <span class="text-danger" *ngIf="nameOnAccount?.errors?.['pattern']">*Name on Account should
                                        be valid</span>
                                </div>
                                <br><br>
                                <input formControlName="routingNumber" type="text" class="form-control"
                                    id="routingnumber" placeholder="Routing Number" pattern="">
                                <div *ngIf="routingNumber?.invalid && routingNumber?.touched">
                                    <span class="text-danger" *ngIf="routingNumber?.errors?.['required']">*Routing Number is
                                        required</span>
                                    <span class="text-danger" *ngIf="routingNumber?.errors?.['pattern']">*Routing Number should
                                        be valid</span>
                                </div>
                                <br><br>
                                <input formControlName="accountNumber" type="text" class="form-control"
                                    id="accountnumber" placeholder="Account Number" pattern="">
                                <div *ngIf="accountNumber?.invalid && accountNumber?.touched">
                                    <span class="text-danger" *ngIf="accountNumber?.errors?.['required']">*Account Number is
                                        required</span>
                                    <span class="text-danger" *ngIf="accountNumber?.errors?.['pattern']">*Account Number should
                                        be valid</span>
                                </div>
                                <br><br>

                                <select type="button" formControlName="accountSubType" class="form-control">
                                    <option disabled selected value>..Select Account Sub Type..</option>
                                    <option *ngFor="let accountSubType of accountSubTypes">{{accountSubType}}</option>
                                </select>
                                <div class="error-block" *ngIf="handleError('accountSubType', 'required')">
                                    You must provide account sub type!
                                </div>
                                <br><br>
                                <select type="button" formControlName="isExternalAccount" class="form-control">
                                    <option disabled selected value>.....Is External Account.....</option>
                                    <option *ngFor="let isExternalAccount of isExternalAccounts">{{isExternalAccount}}</option>
                                </select>
                                <div class="error-block" *ngIf="handleError('isExternalAccount', 'required')">
                                    You must provide!
                                </div>



                            </div><br>

                           
                            <div>
                                <button type="submit" [disabled]="!-saveCustomerForm.valid" (click)="saveCustomer()"
                                    class="btn btn-primary w-100">Save Customer</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

savecust.component.ts savecust.component.ts 文件

import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { SavecustService } from 'src/app/services/savecust.service';
@Component({
  selector: 'app-savecust',
  templateUrl: './savecust.component.html',
  styleUrls: ['./savecust.component.css']
})
export class SavecustComponent implements OnInit {
  statusList: any = ['active', 'inactive']
  accountSubTypes: any = ['savings', 'checking']
  isExternalAccounts: any = ['no', 'yes']

  constructor(private router: Router,
    private fb: FormBuilder,
    private http: HttpClient,
    private savecustService: SavecustService,) { }

  ngOnInit(): void {
  }

  saveCustomerForm = this.fb.group({
    name: ['', [Validators.required, Validators.pattern]],
    email: ['', [Validators.required, Validators.pattern]],
    phone: ['', [Validators.required, Validators.pattern]],
    addressLine1: ['', [Validators.required, Validators.pattern]], 
    // addressLine2: ['', ],
    // addressCity: ['', ],
    addressState: ['', [Validators.required, Validators.pattern]],
    addressCountry: ['', [Validators.required, Validators.pattern]],
    addressZip1: ['', [Validators.required, Validators.pattern]],
    // addressZip2: ['', ],
    ssn: ['', [Validators.required, Validators.pattern]],
    customerReference: ['', [Validators.required, Validators.pattern]], 
    selectStatus: ['', [Validators.required, Validators.pattern]],
    nameOnAccount: ['', [Validators.required, Validators.pattern]], 
    routingNumber: ['', [Validators.required, Validators.pattern]],
    accountNumber: ['', [Validators.required, Validators.pattern]], 
    accountSubType: ['', [Validators.required, Validators.pattern]], 
    isExternalAccount: ['', [Validators.required, Validators.pattern]] 
  },)


  public handleError = (FormControlName: string, errorName: string) => {
    return this.saveCustomerForm.controls[FormControlName].hasError(errorName);
  }

  get name(){
    return this.saveCustomerForm.get("name")
  }

  get email(){
    return this.saveCustomerForm.get("email")
  }

  get phone(){
    return this.saveCustomerForm.get("phone")
  }

  get addressLine1(){
    return this.saveCustomerForm.get("addressLine1")
  }

  get addressState(){
    return this.saveCustomerForm.get("addressState")
  }

  get addressCountry(){
    return this.saveCustomerForm.get("addressCountry")
  }

  get addressZip1(){
    return this.saveCustomerForm.get("addressZip1")
  }

  get ssn(){
    return this.saveCustomerForm.get("ssn")
  }

  get customerReference(){
    return this.saveCustomerForm.get("customerReference")
  }

  get selectStatus(){
    return this.saveCustomerForm.get("selectStatus")
  }

  get nameOnAccount(){
    return this.saveCustomerForm.get("nameOnAccount")
  }

  get routingNumber(){
    return this.saveCustomerForm.get("routingNumber")
  }

  get accountNumber(){
    return this.saveCustomerForm.get("accountNumber")
  }

  get accountSubType(){
    return this.saveCustomerForm.get("accountSubType")
  }

  get isExternalAccount(){
    return this.saveCustomerForm.get("isExternalAccount")
  }

  saveCustomer(){
    console.log(this.saveCustomerForm.value);
    this.http.post<any>("http://localhost:13163/fasterpayments/v1/customers",
    this.saveCustomerForm.value)
      .subscribe(res => {
        alert("Customer saved successfully");
      },err=>{
        alert("something went wrong")
      })
  }

}

savecust.model.ts savecust.model.ts

export class Savecust {
    id!: string;
    name!: string;
    email!: string;
    phone!: string;
    addressLine1!: string;
    addressLine2!: string;
    addressCity!: string;
    addressState!: string;
    addressCountry!: string;
    addressZip1!: string;
    addressZip2!: string;
    ssn!: string;
    customerReference!: string;
    status!: string;
    nameOnAccount!: string;
    routingNumber!: string;
    accountNumber!: string;
    accountSubType!: string;
    isExternalAccount!: string;
}

savecust.service.ts保存服务.ts

import { HttpClient, HttpHeaders } from "@angular/common/http";
import { Injectable } from '@angular/core';
import { Savecust } from "../models/savecust.model";


const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

@Injectable({
  providedIn: 'root'
})

export class SavecustService {
  constructor(private http: HttpClient) { }

  createAuthorizationHeader(headers: HttpHeaders) {
    headers.append('Authorization', 'Basic ');
  }

  public savecustUrl = "http://localhost:13163/fasterpayments/v1/customers";


  public saveCustomer(savecust: any) {
    let headers = new HttpHeaders();
    return this.http.post<Savecust>(
      this.savecustUrl, savecust, {
        headers: headers
      });
  }

  get(savecustUrl: string) {
    let headers = new HttpHeaders();
    this.createAuthorizationHeader(headers);
    return this.http.get(savecustUrl, {
      headers: headers
    });
  }
  
}

app-routing.module.ts应用程序路由.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { SavecustComponent } from './components/savecust/savecust.component';

const routes: Routes = [
  { path: 'savecust', component: SavecustComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

first your method createAuthorizationHeader() should return a value it can be like this首先你的方法 createAuthorizationHeader() 应该返回一个值,它可以是这样的

 createAuthorizationHeader(headers: HttpHeaders) {
headers.append('Authorization', 'Basic ');

return headers } second, you should refector ur saveCustomer method like this return headers } 第二,你应该像这样重构你的 saveCustomer 方法

    public saveCustomer(savecust: any) {
    let headers = new HttpHeaders();
headers=this.createAuthorizationHeader(headers)
    return this.http.post<Savecust>(
      this.savecustUrl, savecust, {
        headers: headers
      });
  }

i can suggest another solution for you, u can use an interceptor to itercept all the http request and add the desired headers, u can learn about angular http interceptors here https://angular.io/api/common/http/HttpInterceptor我可以为您建议另一种解决方案,您可以使用拦截器来拦截所有 http 请求并添加所需的标头,您可以在此处了解 angular http 拦截器https://angular.io/api/common/http/HttpInterceptor

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Angular 2-使用TypeScript在一条路径中设置多个组件而不丢失数据的最佳方法是什么 - Angular 2- what is the best way to set multiple components in one path without losing data using TypeScript 将文件从 angular 11 形式传递到 asp.net 核心 5 web Z8A5DA552ED12654E72Z3 的最佳方式是什么 - What is the best way pass file from angular 11 form to asp.net core 5 web api 在 Angular CLI 中使用 Bootstrap 的最佳方法是什么 - What is the best way for using Bootstrap in Angular CLI 使用Angular Http标头发送凭据数据的正确方法是什么? - What is the correct way of sending credentials data using Angular Http Headers? Angular 1.5和Typescript:准备角度2的最佳方法 - Angular 1.5 and Typescript: best way to prepare to angular 2 Angular 6- 将数据从模板传递到控制器的最佳方式? - Angular 6- Best way to pass data from template to controller? 使用 Typescript 在 Angular 中处理环境的最佳方法 - The best way to handle environments in Angular with Typescript 将 angular 6 升级到 9 的最佳方法是什么? - What is the best way to upgrade angular 6 to 9? 使用RxJS从HTTP请求在Angular组件之间传递数据的正确方法是什么? - What is the correct way to pass data between Angular components from an HTTP request using RxJS? 使用 Angular 的 HttpClient 进行同步调用的最佳方法是什么? - What is the best way to make synchronous calls using Angular's HttpClient?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM