Angular2 - http:// localhost:4200 /正在附加api调用为什么?

问题描述:

刚开始学习angular2跟着heroes教程。我正在做一个创建请求,URL非常好,参数很好。但我仍然困惑为什么http://localhost:4200/正在追加我的API调用,并因为该URL得到完全改变,并调用failed.please揭露了这个问题。我GOOGLE了很多,但可以找到原因。Angular2 - http:// localhost:4200 /正在附加api调用为什么?

我的创建方法

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

+0

结果网址如何显示,以及您在哪里看到附加内容? –

+0

在我的控制台先生等待让我添加一个屏幕截图 –

+0

请参阅图像 –

您需要添加协议您的网址。否则,它是一个相对URL:

.post('http://localhost/usmanProject/api/web/v1/users?access-token=n-EJtZiejtz5RSVWe-U14G4kCnPWMKf0', user, { headers: this.headers }) 

http://localhost:4200/是该页面最初从加载的URL。

您应该添加完整的URL

.post('//localhost:4200/usmanProject/api/web/v1/users?access-token=n-EJtZiejtz5RSVWe-U14G4kCnPWMKf0', user, { headers: this.headers }) 

.post('http://localhost:4200/usmanProject/api/web/v1/users?access-token=n-EJtZiejtz5RSVWe-U14G4kCnPWMKf0', user, { headers: this.headers }) 

或根本

.post('usmanProject/api/web/v1/users?access-token=n-EJtZiejtz5RSVWe-U14G4kCnPWMKf0', user, { headers: this.headers }) 

遇到过这个问题没有主机部分和解决它通过相关分离通过创建一个app.settings.ts文件,该文件将包含api所在的终点VED从

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

然后创建一个服务,并导入app.settings如下

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`); 
} 
} 

在你app.component.html添加触发API调用的函数

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

然后在你的app.component.ts你写你的方法

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