加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何使用Angular 2访问API?

发布时间:2020-12-17 18:05:41 所属栏目:安全 来源:网络整理
导读:我希望能够在我的Angular 2应用程序之外导航到mywebsite.com/api.这应该带我到同一服务器托管的API应用程序. 这是我目前的路线设置. export const routes: Routes = [ {path: '',redirectTo: '/home',pathMatch: 'full'},{path: 'home',component: HomeCompo
我希望能够在我的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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读