How to make AJAX call with angular2(ts)?

2020-02-04 07:43发布

问题:

How to make AJAX call with angular2(ts)? I read the tutorial on angularjs.org. But there is nothing about AJAX. So I really want to know how to make AJAX call with angular2(ts).

回答1:

You will want to look at the api docs for the http module. The http class can get resources for you using AJAX. See the Angular HttpClient Guide for more examples.

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);
  }
}


回答2:

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
                );                
    }    
}


回答3:

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);
  }


回答4:

AJAX is fully transparent in angularjs, see the links and examples below.

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/$resource

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


标签: angular