2016-12-02 86 views
5

我希望能夠在我的Angular 2應用程序外導航到mywebsite.com/api這應該帶我到同一個服務器上託管的API應用程序。如何使用Angular 2訪問API?

這是我目前的路線設置。

export const routes: Routes = [ 
    {path: '', redirectTo: '/home', pathMatch: 'full'}, 
    {path: 'home', component: HomeComponent}, 
    {path: 'registration', component: RegistrationComponent}, 
    {path: '**', redirectTo: '/home', pathMatch: 'full'} 
]; 

如何排除路徑,因爲我不需要組件或模板?

+0

PHP ANE xample你是說你想打一個API終點?您需要使用angular2的http包來執行此操作。什麼是你使用的後端? – wuno

+0

我正在主持一個接收和回覆json的php應用程序。 – mcfresh

+0

所以你試圖做的是擊中api結束點然後處理響應權? – wuno

回答

0

angular2您將使用http docs here

import { Http, Response, Headers } from '@angular/http'; 

export class ProfileComponent implements OnInit { 

    constructor(private router: Router, private auth: Auth, private http: Http ) { } 

    private personalSubmit() { 
     let headers = new Headers(); 
     headers.append('Content-Type', 'application/json'); 
     return this.http 
     .post('http://localhost:4200/api/apiEndpointURL', 
     this.personal, 
     { headers: headers }) 
     .map((res:Response) => res.json()) 
     .subscribe((res)=>{ 
      //do something with the response here 
      console.log(res); 
     }); 
    } 

這是提交表單的一個例子讓api電話。在這種情況下,表格中的值爲post,響應爲console.logterminal。這是一個使用node.js後端的例子。我不確定php需要更改什麼,但最終您需要http package。唯一可能需要根據返回的內容更改應用程序類型。

我相信你用這個作爲應用程序類型php

headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); 

我發現使用

+0

謝謝,我將在未來與api通信,但我也希望能夠託管php api,以便移動應用程序可以與它通信。似乎我不得不放開一條路線,但角度的文檔並不明確。 – mcfresh

+0

在節點中,爲後端創建路由,以便存在一個終點。但是,如果您使用angular2作爲單獨的應用程序,據我所知,http方法將進行調用。 api的終點必須存在於api端,所以當你用你製作的帖子打開它時,它就會熄滅。我可以告訴你它是如何在node/express中創建的。最重要的是。請確保您閱讀了有關http的內容,以便了解如何使用數據構建函數。 http實際上很容易使用。但是你必須在PHP端創建一些端點。 – wuno

+0

如果api在同一臺服務器上,上面的代碼會工作嗎? 基本上,當你點擊htttp:// mywebsite/** api **時,它會轉到php文件(api endpoint) – mcfresh