代理服務用於在瀏覽器中進行測試,以避免在使用外部API時出現No 'Access-Control-Allow-Origin' header is present on the requested resource
錯誤。但是這不是設備上的問題,因此不需要此代理服務。所以,在設備上使用直接調用您的API網址,而不是調用http://localhost:8100
。
如果您想在設備和瀏覽器上進行測試,只需檢查Cordova是否可用(並且您位於設備上),然後定義要使用的URL。事情是這樣的:
import {Injectable} from '@angular/core';
import {Headers, Http} from '@angular/http';
import {Platform} from 'ionic-angular';
import 'rxjs/add/operator/toPromise';
import ...
@Injectable()
export class AccessService {
private headers = new Headers({'Content-Type': 'application/json'});
private apiUrl = '/v1/';
constructor(private http: Http,
public platform: Platform) {
if (this.platform.is('cordova')) { // <<< is Cordova available?
this.apiUrl = 'https://api.instagram.com/v1/';
}
}
login(username: string, password: string): Promise<string> {
let postParams = {
username: username,
password: password
};
return this.http
.post(this.apiUrl + 'login', postParams, this.headers)
.toPromise()
.then(response => response.json().devicetoken as string)
.catch(this.handleError);
}
}
...
}
我又如何能設置配置 –
任何你想要一個API網址:在你的組件,在接入服務或一個常數。我用更廣泛的例子編輯了我的答案(也將它改爲Ionic 2)。希望這給你一個更好的主意。我剛剛製作了這個例子,但沒有經過測試。只是想給你一個想法。 – JanP
更高級的方法是使用自動化工具,如gradle – JanP