如何使用angular2(ts)进行AJAX调用?

时间:2016-01-15 01:16:34

标签: angular

如何使用angular2(ts)进行AJAX调用? 我阅读了angularjs.org上的教程。但是AJAX没有任何内容。 所以我真的想知道如何使用angular2(ts)进行AJAX调用。

4 个答案:

答案 0 :(得分:20)

您需要查看api docs for the http modulehttp类可以使用AJAX为您获取资源。有关更多示例,请参阅Angular HttpClient Guide

import { Component } from '@angular/core';
import { Http } from '@angular/http';

@Component({
  selector: 'http-app',
  templateUrl: 'people.html'
})
class PeopleComponent {
  constructor(http: Http) {
    http.get('people.json')
      // Call map on the response observable to get the parsed people object
      .map(res => res.json())
      // Subscribe to the observable to get the parsed people object and attach it to the
      // component
      .subscribe(people => this.people = people);
  }
}

答案 1 :(得分:8)

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';

import { Http, Response, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';

@Component({
    selector: 'dashboard',
    templateUrl: './dashboard.component.html',
    styleUrls: ['./dashboard.component.css'],
    providers: [RemoteService]
})

export class DashboardComponent implements OnInit {
    allData = [];
    resu: string;
    errData: string;
    name: string = "Deepak";

    constructor(private http: Http){}

    ngOnInit(){}

    onSubmit(value: any) {
    //console.log(value.message);
    let headers = new Headers({ 'Content-Type': 'application/json'});
    let options = new RequestOptions({ headers: headers });
    let body = JSON.stringify(value);
    this.http.post('127.0.0.1/myProject/insertData.php', body, headers)
                .subscribe(
                    () => {alert("Success")}, //For Success Response
                    err => {console.error(err)} //For Error Response
                );                
    }    
}

答案 2 :(得分:1)

JSON-data.service.ts

import { Injectable } from '@angular/core';
import { Http, Response, RequestOptions, Headers } from "@angular/http";
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class JsonDataService {
  errorMessage: any;

  constructor(private http: Http) {
  }

 getData(): Observable<JsonData[]> {
    console.log('Retriving Data from Server.......');
    return this.http.get('http://883.82.3:8086/restfullDataApi/UserService/jsondata')
      .map(this.extractData)
      .catch(this.handleError);
  }

getSolrData() {
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    let url = "http://883.8.2:8086/PI3_Solr_WebService/solrService"; /
    return this.http.post(url).map((res: Response) => res.json());
  }
   let body = res.json();
    return body || [];
  }

  private handleError(error: any) {
    // In a real world app, we might use a remote logging infrastructure
    // We'd also dig deeper into the error to get a better message
    let errMsg = (error.message) ? error.message :
      error.status ? `${error.status} - ${error.statusText}` : 'Server error';
    console.error(errMsg); // log to console instead
    alert("Server Error!");
    return Observable.throw(errMsg);
  }

答案 3 :(得分:-5)

AJAX在angularjs中是完全透明的,请参阅下面的链接和示例。

https://docs.angularjs.org/api/ng/service/ $ HTTP

$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

https://docs.angularjs.org/api/ngResource/service/ $资源

var User = $resource('/user/:userId', {userId:'@id'});
User.get({userId:123}, function(user) {
  user.abc = true;
  user.$save();
});