Kingsley
Kingsley

Reputation: 365

Making Angular 6 php mysql api calls

I'm new to the Angular World (I have been using Angularjs all the while).

I want to make a login app and would like to make an api call to the backend (the php and mysql server, running locally on my computer).

In Angularjs, I would write a service like:

(function () {
  'use strict';
angular.module('module name').service('userService', user);

function user ($resource) {
return $resource('api/users', {}, {update: {method: PUT}});
}
})();

With that, I could make calls to the server by simply calling

 $onInit = function () {
       var user = new userService();
       user.$save(.....) //post request.
       user.$update(....) //put request.
    }

In angular, I see things are different. I can't seem to connect to the server using the same code I wrote for AngularJS.

Making an api call like:

this.http.post('api/users', userAccess.value).subscribe(data => {
console.log(data);
}

gives me post http://localhost:3001/api/users 404 not found error.

PS. userAccess is the ReactiveForm formGroup object containing an email address and a password.

The api code sits in a folder under src folder, next to app folder. It has 3 files, api.php, rest.inc.php and the htaccess file. It's my own implementation of an api interface.

Here is my LoginComponent.ts..

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { HttpClient } from '@angular/common/http';

@Component({
    selector: 'app-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.sass']
})
export class LoginComponent implements OnInit {
    hide: boolean = true;

    constructor(
        private fb: FormBuilder,
        private http: HttpClient
    ) { }

    ngOnInit() {
    }

    userAccess: FormGroup = this.fb.group({
        email: ['', [Validators.email, Validators.required]],
        password: ['', [Validators.required]]
    })

    onSubmit = () => {
        this.http.post('api/users', 
            {
                username: this.userAccess.value.email,
                encryption: this.userAccess.value.password
            }
        ).subscribe(data => {
            console.log(data);            
        });        
    }

    getEmailMessage = () => {
        return this.userAccess.controls['email'].hasError('required')  ? 'Please enter an email address'  :  this.userAccess.controls['email'].hasError('email') ? 'Not a valid email' : '';
    }

}

And here is the folder structure..

enter image description here

Here is the snapshot of the api folder.. enter image description here

This is the error I get no matter what path I put... enter image description here

How should I go about doing this the right way?

Upvotes: 1

Views: 3454

Answers (4)

Kingsley
Kingsley

Reputation: 365

I got it working. I just added a proxy configuration and run the server on a different port

Upvotes: 0

Matthias Cruciani
Matthias Cruciani

Reputation: 9

From what I see in the error log, you get this 404 because you are not calling the good url, you try to reach localhost:4200 but you want to call localhost:3001.

On localhost:4200 you certainly have your angular app running if you launched it using the "ng serve" command, because ng serve uses port 4200.

Since you are not specifying the full path in your post, it is trying to reach the url from where you are calling it, here 4200.

So to fix that you should specify the full path in your post like this:

this.http.post('http://localhost:3001/api/users', userAccess.value).subscribe(data => {console.log(data);}

this should fix it, at least it should call your php api.

Upvotes: 0

Exterminator
Exterminator

Reputation: 1246

path you have defined here is incorrect.

this.http.post('http://localhost/project_name/api/api.php', 
            {
                username: this.userAccess.value.email,
                encryption: this.userAccess.value.password
            }
        ).subscribe(data => {
            console.log(data);            
        }); 

change the path of the api folder, bring it to the root folder(at the same level of e2e folder), then do as mentioned.

add these lines to the php file

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: X-Requested-With');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Content-Type: application/json');

and to get the data in post request use this

$data = json_decode(file_get_contents("php://input"));

Upvotes: 0

CuriousMind
CuriousMind

Reputation: 3173

You are getting 404 error that does mean you are able to call HTTP service from your angular code. Please check whether the URL for your API is correct or not. (Hint: Use Browser tools)

In Angular, to access API it is recommended to create a separate service class which can be later injected wherever you require it e.g. component.

You can create service class using following CLI command

ng g s NameOfYourService

Later int the constructor of your service simply inject a reference of HttpClient. Refer below example

constructor(private httpClient:HttpClient)

you can use this reference as shown below

public performUserLogin(cred:Credentials):Promise<void> {
   return this.httpClient.post<void>('http://yourhost:yourport/api_path', cred).toPromise();
}

Note you have choice to either return promise or Observable.

For more details you can go through the official documentation.

Upvotes: 1

Related Questions