2017-02-22 62 views
1

工作,而在設備上運行的應用程序不會得到API網址 不獲取網址Ionic2 proxyUrl不會對設備

我用下面的編碼

{ 
    "v2": true, 
    "typescript": true, 
    "proxies": [ 
    { 
     "path": "/api", 
     "proxyUrl": 'api url here' 
    } 
    ] 
} 

請給任何suggustions

回答

1

代理服務用於在瀏覽器中進行測試,以避免在使用外部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); 
     } 
    } 

    ... 
} 
+0

我又如何能設置配置 –

+0

任何你想要一個API網址:在你的組件,在接入服務或一個常數。我用更廣泛的例子編輯了我的答案(也將它改爲Ionic 2)。希望這給你一個更好的主意。我剛剛製作了這個例子,但沒有經過測試。只是想給你一個想法。 – JanP

+0

更高級的方法是使用自動化工具,如gradle – JanP

相關問題