如何使用Angular 2访问API?

前端之家收集整理的这篇文章主要介绍了如何使用Angular 2访问API?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我希望能够在我的Angular 2应用程序之外导航到mywebsite.com/api.这应该带我到同一服务器托管的API应用程序.

这是我目前的路线设置.

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

如何排除路径,因为我不需要组件或模板?

解决方法

在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,在这种情况下,响应是console.log到终端.这是使用node.js后端的示例.我不确定什么需要更改为PHP但最终你将需要http包.唯一的问题是您可能需要根据返回的内容更改应用程序类型.

我相信你用PHP作为应用程序类型,

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

我发现了使用PHP的xample

猜你在找的Angularjs相关文章