Ronny A.
Ronny A.

Reputation: 1

How to make call and if api returns error 404, will open modal

I am first trying to verify the url is good. If it is, it will return a sign from url. If it returns a error 404, i want it to open up the already established modal tell user what to do.

I am using Angular to write the code. I'm not exactly sure how to do this.

Here is what I have in sign-form.component.ts:

import {Sign} from '../sign';
import {environment} from './../../environments/environment';
import {ActivatedRoute, ParamMap} from '@angular/router';
import {PalModal} from '@pallet/angular';


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

  constructor(private route: ActivatedRoute) {
    this.getStoreNumber();
  }

  submitted = false;

  model = new Sign('', '');


  @ViewChild('modalId', {static: false}) myModal: PalModal;





  ngOnInit() {


  }

  getStoreNumber() {
    this.route.queryParamMap.subscribe(
        (params: ParamMap) => {
          this.model.store = params.get('store');
        }
    )
  }

  getSign() {
    this.submitted = true;
    const sign = this.model;

    this.myModal.open();


    const STORE_REGEXP = /^-?\d{3,4}$/;
    const PRODUCTID_REGEXP = /^[-0-9a-zA-Z]+$/;

    if (!sign.store
        || !sign.productId
        || !STORE_REGEXP.test( sign.store )
        || !PRODUCTID_REGEXP.test( sign.productId )) {
      return;
    }

    const store = sign.store.length === 3 ? '0' + sign.store : sign.store;
    let productId = sign.productId.toUpperCase();
    const SKU_REGEXP = /^[-0-9]+$/;
    let productType;
    if (SKU_REGEXP.test( productId )) {
      productType = 'sku';
      productId = productId.split( '-' ).join( '' );
    } else {
      productType = 'model';
    }



    const url = environment.digitalSignageServiceUri + '/ESL/pdf/store/' + store + '/' + productType + '/' + productId;
    window.open(url, '', '');

  }

  onClick() {
    this.myModal.close();
  }
}

Upvotes: 0

Views: 550

Answers (1)

Razvan
Razvan

Reputation: 45

You can use HttpInterceptor to intercept the request and open the modal.

 intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
      tap(
        () => { },
        (error: any) => {
          if (error instanceof HttpErrorResponse) {
            if (error.status === 404) {
             //open modal
            }
          }
        }
      )
    );
  }

Upvotes: 1

Related Questions