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);
}
You need to add your protocol for your URL. Otherwise, it's a relative URL:
.post('http://localhost/usmanProject/api/web/v1/users?access-token=n-EJtZiejtz5RSVWe-U14G4kCnPWMKf0', user, { headers: this.headers })
http://localhost:4200/
is the url the page is initially loaded from.
You should either add the full url like
.post('//localhost:4200/usmanProject/api/web/v1/users?access-token=n-EJtZiejtz5RSVWe-U14G4kCnPWMKf0', user, { headers: this.headers })
or
.post('http://localhost:4200/usmanProject/api/web/v1/users?access-token=n-EJtZiejtz5RSVWe-U14G4kCnPWMKf0', user, { headers: this.headers })
or no host part at all
.post('usmanProject/api/web/v1/users?access-token=n-EJtZiejtz5RSVWe-U14G4kCnPWMKf0', user, { headers: this.headers })
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);
});
}
Your Url should be like url:string ="www.example.com";
It should not be like url:string =" 'www.example.com' ";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.