Angular2 - http://localhost:4200/ being appended with api call why?

Viewed 6353

just start learning angular2 followed the heroes tutorial. I am making a create request, the URL is perfectly fine, the parameters are fine. But I am still confused why http://localhost:4200/ is being appended with my API call, and because of that the URL gets totally changed, and the calls failed.please shed some light over this issue. I googled a lot but could find the reason.

My Create Method

 create(user: object): Promise<any> {
    return this.http
        .post('localhost/usmanProject/api/web/v1/users?access-token=n-EJtZiejtz5RSVWe-U14G4kCnPWMKf0', user, { headers: this.headers })
        .toPromise()
        .then(res => res.json().data)
        .catch(this.handleError);
}

enter image description here

4 Answers

Your Url should be like url:string ="www.example.com";

It should not be like url:string =" 'www.example.com' ";

Experienced this problem and solved it through separation of concern by creating a app.settings.ts file that will contain the end point to where the api is being served from

export class AppSettings {
   public static get FOLDER_ENDPOINT(): string {
     return 'http://127.0.0.1:8000';
   } 
}

Then create a service and import the app.settings as below

import { Injectable } from '@angular/core';
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs/Observable";
import { HttpHeaders } from '@angular/common/http/src/headers';
import { Http, Response, RequestOptions, ResponseContentType } from 
'@angular/http';
import 'rxjs/Rx';
import { AppSettings } from '../app.settings';


@Injectable()
export class FormsubmitService {

constructor(private http: HttpClient) { }

listAll(data: any): Observable<any> {
  return this.http
    .get(`${AppSettings.FOLDER_ENDPOINT}/list-files`);
 }
}

In your app.component.html add a function that triggers the api call

<button (click)="loadData()" class="btn btn-primary pull-right">load data</button>

Then in your app.component.ts you write your method

loadData() {
  this._fbService.listAll('').subscribe(data => {
   console.log('Data returned', data);
  });
}
Related