2016-12-02 87 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