Angular 7 HTTP post example

Example 1: angular post request

ngOnInit() {          
     this.http.post<any>('https://reqres.in/invalid-url', { title: 'Angular POST Request Example' }).subscribe({
        next: data => {
            this.postId = data.id;
        },
        error: error => {
            this.errorMessage = error.message;
            console.error('There was an error!', error);
        }
    })
}

...

interface Article {
    id: number;
    title: string;
}

Example 2: angular get response headers

this.authenticationService.login(this.f.email.value, this.f.password.value)
  .pipe(first())
  .subscribe(
    (data: HttpResponse<any>) => {
      console.log(data.headers.get('authorization'));
    },
    error => {
      this.loading = false;
    });

At my Service Side.

return this.http.post<any>(Constants.BASE_URL + 'login', {username: username, password: password},
  {observe: 'response' as 'body'})
  .pipe(map(user => {
       return user;
  }));

Example 3: angularjs make post request

var url = 'posturl', data = 'parameters',config='contenttype';

$http.post(url, data, config).then(function (response) {

// This function handles success

}, function (response) {

// this function handles error

});

Example 4: angular material mat-error on http request

// first define our formcontrol object
control = new FormControl('', [Validators.required])

//http method:
submit() {
  //call api
  // assume you got an error (Unauthorized, BadRequest, ...)
  //this set control to errored status and thus,
  //mark formcontrol/formgroup as invalid
  this.control.setErrors({error_key: true})
}

// in your html code :
<mat-form-field>
  <mat-label>Control</mat-label>
  <input type="text" formControlName="control" matInput />
  <mat-error *ngIf="control.hasError('required')">
  	Control cannot be empty
  </mat-error>
  <mat-error *ngIf="control.hasError('error_key')">
  	My custom error message
  </mat-error>
</mat-form-field>

Example 5: interceptor in angular 8

interface HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
}

Tags:

Misc Example