2

I am trying to call my api as follow:

MyComponent.ts:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { ActivatedRoute } from '@angular/router';
import { Api } from '../../services/Api';
import { Account } from '../../models/Account';

@Component({
  selector: 'app-account-individual',
  templateUrl: './account-individual.component.html',
  styleUrls: ['./account-individual.component.css']
})
export class AccountIndividualComponent implements OnInit {

  account_id: number;
  account: Account = new Account();

  constructor(private route: ActivatedRoute, private proxy: Api) {
    this.proxy.postClient('api-get?call=get-account', { "id": 1 }).subscribe(
      res => {
        console.log(res);
      }
    );
  }

  ngOnInit() {
    this.route.params.subscribe(params => {
      this.account_id = params['id'];
    });
  }
}

Api.ts:

import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import * as Globals from 'Globals';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class Api {

    api_url = "http://localhost/MyProject/";

    constructor(private http: Http, private httpClient: HttpClient) { }

    fetchData(url) {
        return this.http.get(this.api_url + url).map(this.extractData).catch(this.handleErrorPromise);
    }

    postClient(url: string, data?: any){
        return this.httpClient.post(this.api_url + url, data);
    }

    private extractData(res: Response) {
        let body = res.json();
        return body||{};
    }

    private handleErrorObservable(error: Response | any) {
        console.error(error.message || error);
        return Observable.throw(error.message || error);
    }

    private handleErrorPromise(error: Response | any) {
        console.error(error.message || error);
        return Promise.reject(error.message || error);
    }
}

server CORS:

public function actionApiGet($call){
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: x-test-header, Origin, X-Requested-With, Content-Type, Accept');
        $data = json_decode(file_get_contents('php://input'), true);
...

but the api is called twice, the first call method is OPTIONS while the second is POST

4
  • 3
    That's not related to Angular. The browser does that for CORS requests. You need to configure your server to properly handle OPTIONS request. Search for CORS to find more details. Commented Jan 2, 2018 at 11:31
  • @GünterZöchbauer please check update and see the CORS Commented Jan 2, 2018 at 11:34
  • What's the problem? You won't be able to get rid of the OPTIONS request, except if you change your configuration to not have a CORS situation, which means the index.html is loaded from the same host and port as what this.api_url + url results to. Commented Jan 2, 2018 at 11:41
  • Its because of incorrect CORS fix enable-cors.org Commented Jan 2, 2018 at 12:42

1 Answer 1

2

This is the expected behavior if you are calling some service hosted in other server, the browser needs validate if the current client is hosted in a valid server

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.