【问题标题】:How to access an API with Angular 2?如何使用 Angular 2 访问 API?
【发布时间】:2016-12-02 00:34:48
【问题描述】:

我希望能够在我的 Angular 2 应用程序之外导航到 mywebsite.com/api这应该会将我带到托管在同一服务器中的 API 应用程序。

这是我当前的路线设置。

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

由于不需要组件或模板,我将如何排除路径?

【问题讨论】:

  • 你是说你想访问一个 api 端点吗?您需要使用 angular2 的 http 包来执行此操作。你用的是什么后端?
  • 我正在托管一个接收和回复 json 的 php 应用程序。
  • 那么你要做的是点击 api 端点然后处理响应吧?
  • 是的,没错

标签: angular angular2-routing angular2-services


【解决方案1】:

angular2 中,您将使用http docs here 拨打api

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

这是发布表单的示例。表单中的值为post,在这种情况下,对terminal 的响应是console.log。这是一个使用 node.js 后端的示例。我不确定php 需要更改什么,但最终您将需要http package。唯一的事情是您可能需要根据返回的内容更改应用程序类型。

我相信对于php,您将其用作应用程序类型,

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

我找到了一个使用 php 的示例

【讨论】:

  • 谢谢,我以后会和 api 通信,但我也希望能够托管 php api,以便移动应用程序可以与之通信。看来我必须打开一条路线,但角度文档并不清楚。
  • 在节点中,您为后端创建路由,因此存在一个端点。但是,据我所知,如果您将 angular2 用作单独的应用程序,则 http 方法将进行调用。 api 端点必须存在于 api 端,因此当您使用您发布的帖子点击它时它会触发。我可以向您展示它是如何在 node/express 中创建的。最重要的是。确保您阅读了有关 http 的内容,以便了解如何使用您的数据形成函数。 http其实很容易使用。但是你必须在 php 端创建一些端点。
  • 如果 api 在同一个服务器上,上面的代码会起作用吗?基本上,在网络应用程序上,当您点击 http://mywebsite/**api** 时,它会转到 php 文件(api 端点)
  • 就发出请求而言,您正在发出 http 请求。话虽如此,根据服务器的配置,有些事情可能会阻止这样的请求
  • @mcfresh 这是一个 angular 2 问题,有人从 angular2 发布到 larval 后端。我认为这也可能有助于您在 angular2 端编写查询stackoverflow.com/q/40934415/2218253 我理解您没有使用 larval 后端,但我认为它可能有助于导致它仍在调用 php 后端。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-04
  • 1970-01-01
  • 2020-11-07
  • 1970-01-01
  • 2020-09-09
  • 1970-01-01
  • 2017-05-24
相关资源
最近更新 更多