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

如何使用angular2 / http进行ajax调用?

发布时间:2020-12-17 08:46:26 所属栏目:安全 来源:网络整理
导读:我正在使用Angular 2.0.0-beta.0和typescript.我能够在没有任何问题的情况下使用window [‘fetch’]开启ajax调用(我不需要使用早期版本中所需的任何变通方法.) 但我无法使用angular2的http进行相同的ajax调用. 以下是演示此问题的代码.项目文件夹中有三个文
我正在使用Angular 2.0.0-beta.0和typescript.我能够在没有任何问题的情况下使用window [‘fetch’]开启ajax调用(我不需要使用早期版本中所需的任何变通方法.)

但我无法使用angular2的http进行相同的ajax调用.

以下是演示此问题的代码.项目文件夹中有三个文件index.html,以及名为app的子文件夹中的boot.ts和app.component.ts.

app.component.ts:

import {Http,HTTP_PROVIDERS} from 'angular2/http';
import {Component} from 'angular2/core';

@Component({
    selector: 'my-app',providers: [HTTP_PROVIDERS],template: '<h1>My First Angular 2 App</h1><button (click)="getTasks()">click</button>{{tasks}}'
})
export class AppComponent { 
    http: Http;
    tasks = [];

    constructor(http: Http) {
        alert(http == null);
        this.http = http;
    }

    getTasks(): void {
        this.http.get('http://localhost:3000/tasks/norender');
            //.map((res: Response) => res.json())

            //it is important to have this subscribe call,since the 
            //request is only made if there is a subscriber 
            .subscribe(res => this.tasks = res);
    }   
}

boot.ts:

import {bootstrap} from 'angular2/platform/browser'
import {HTTP_PROVIDERS} from 'angular2/http';
import {AppComponent} from './app.component'

bootstrap(AppComponent,[HTTP_PROVIDERS]);

index.html的:

<!DOCTYPE html>
<html>
  <head>
    <title>Angular 2 QuickStart</title>
    <!-- 1. Load libraries -->
        <script src="https://rawgithub.com/systemjs/systemjs/0.19.6/dist/system.js"></script>
        <script src="https://code.angularjs.org/tools/typescript.js"></script>
        <script src="https://code.angularjs.org/2.0.0-beta.0/angular2-polyfills.js"></script>
        <script src="https://code.angularjs.org/2.0.0-beta.0/Rx.js"></script>
        <script src="https://code.angularjs.org/2.0.0-beta.0/http.dev.js"></script>
        <script src="https://code.angularjs.org/2.0.0-beta.0/angular2.dev.js"></script>

    <!-- 2. Configure SystemJS -->
    <script>
        System.config({
            transpiler: 'typescript',typescriptOptions: {emitDecoratorMetadata: true},packages: {'app': {defaultExtension: 'ts'}} 
        });
        System.import('app/boot')
            .then(null,console.error.bind(console));
    </script>

  </head>

  <!-- 3. Display the application -->
  <body>
    <my-app>Loading...</my-app>
  </body>

</html>
您应该添加一个Http提供程序.你有两个选择:

>在引导程序上:

从’angular2 / http’导入{HTTP_PROVIDERS};

和:

ng.bootstrap(src.SomeComponent,[HTTP_PROVIDERS]);

>在使用该服务的组件上:

从’angular2 / http’导入{HTTP_PROVIDERS};

@零件({

提供者:[HTTP_PROVIDERS]

…})

(编辑:李大同)

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

    推荐文章
      热点阅读