2016-11-08 54 views
-1

我是新的角2.0中我试图调用ajax.But我不能调用ajax按钮单击。请帮我执行以下代码我们如何可以调用角2.0中的ajax url节点

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

@Component({ 
    selector: 'my-app', 
    templateUrl: './templates/login.html'}) 
export class AppComponent { 
    constructor(private http: Http) { } 
} 
+0

[HTTP客户端文档(https://angular.io/docs/ts/latest/guide/server-communication。 HTML) –

回答

1

Ajax调用我理解为HTTP调用/调用HTTP Api。你可以像这样调用你的api。

constructor(private http: Http) { } 

    ngOnInit() { 
     let res = this.getHeroes(); 
     console.log(res); 
    } 

    getHeroes(): Promise<Hero[]> { 
    return this.http.get('http//api.example.com/api/url/here') 
       .toPromise() 
       .then(response => response.json()) 
       .catch(console.log); 
    } 
2

的Html,

<button (click) = 'getstudentbyid(121)'>CLICK</button> 

TS,

import {Component,enableProdMode} from 'angular2/core'; 
    import {Http,Headers} from 'angular2/http'; 
    @Component({ 
     selector: 'my-app', 
     templateUrl: './templates/login.html'}) 
    export class AppComponent { 
    constructor(private http: Http) { } 

    getstudentbyid(id: any): any { 
     var headers = new Headers(); 
     headers.append('Content-Type', 'application/json') 
     this.http.get('http://localhost:3009/api/auth/getstudentbyid/' + id, { headers: headers }) 
      .subscribe(
      result => { 
       if (result.json().error_code == 0) { 
        this.res = result.json().result; 
        this.students = this.res; 
       } 
       else { 
        this.students = result.json().result; 
       } 
      }) 
    } 
} 
相关问题