Как сделать вызов AJAX с помощью angular2 (ts)?
Как сделать вызов AJAX с помощью angular2 (ts)?
Я прочитал учебник по angularjs.org. Но в AJAX ничего нет.
Поэтому я действительно хочу знать, как сделать вызов AJAX с помощью angular2 (ts).
Ответы
Ответ 1
Вам нужно посмотреть api docs для http-модуля. Класс http
может получить ресурсы для вас, используя 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);
}
}
Ответ 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 полностью прозрачен в 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/ $resource
var User = $resource('/user/:userId', {userId:'@id'});
User.get({userId:123}, function(user) {
user.abc = true;
user.$save();
});