Working on a project where the entity gets updated frequently in the database and the ui which is html5 will be displayed using rxjs via rest service.
html5->rxjs->restservice->db
Can someone has experience similar or achieved this ?
My Controller looks like this
import {Component} from 'angular2/core';
import {HomeService} from './home.services';
import {Index} from './index';
#Component({
selector: 'home-app',
providers: [HomeService],
templateUrl: 'MktHome.html',
})
export class HomeComponent {
private indexes: Observable<Index[]>;
constructor(private _service: HomeService){
_service.getIndexes().subscribe(
res => this.indexes = res,
error => alert(" Error is : " + error),
()=> console.log("finished")
);
console.log(this.indexes);
}
generateArray(obj){
return Object.keys(obj).map((key)=>{ return obj[key]});
}
}
Service
import {Injectable, Inject} from 'angular2/core';
import {Http, Response, RequestOptions, Headers, Request, RequestMethod} from 'angular2/http'
import 'rxjs/add/operator/map';
#Injectable()
export class HomeService {
private actionUrl: string;
private headers: Headers;
private requestoptions;
constructor(private _http: Http) {
console.log('Task Service created.', this._http);
this.actionUrl = "http://localhost:8080/index/home";
this.headers = new Headers();
this.headers.append('Content-Type', 'application/json');
this.headers.append("Accept", 'application/json');
}
// Uses http.get() to load a single JSON file
getIndexes(){
this.requestoptions = new RequestOptions({
method: RequestMethod.Get,
url: this.actionUrl,
headers: this.headers})
return this._http.request(new Request(this.requestoptions)).map(res => res.json());
}
}
Thanks
Rafi
Related
I try to program a function but somehow the error pops up:
when I want to .map (res => res.json());
what did I do wrong here? I use the newest Angular Version.
import { Injectable } from '#angular/core';
//import {Http, Headers} from '#angular/http';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import {Contact} from './contact';
import 'rxjs/add/operator/map';
#Injectable({
providedIn: 'root'
})
export class ContactService {
constructor(private http: HttpClient) { }
//retrieving ContactService
getContacts()
{
return this.http.get('http://localhost:3000/api/contacts')
.map(res => res.json());
}
//add contact method
addContact(newContact) {
var headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');
return this.http.post('http://localhost:3000/api/contact', newContact, {headers:headers})
.map(res => res.json());
}
//delete methods
deleteContact(id)
{
return this.http.delete('http://localhost:3000/api/contact'+ id)
.map(res => res.json());
}
}
I believe you're coming from an older version of RxJS and HttpClient. In the latest versions you need the following adjustments.
If you're using newer versions of RxJS, the map should be applied using pipe.
import 'rxjs/add/operator/map'; // <-- deprecated
import { map } from 'rxjs'; // <-- new
return this.http.delete('http://localhost:3000/api/contact'+ id).pipe(
map(res => res.json())
);
In the newer versions of Angular, the res.json() isn't required. The fetched data is already a JS object if it was one. So you can just say
return this.http.delete('http://localhost:3000/api/contact'+ id);
I have an IONIC APP with CORDOVA. I Just want to GET a JSON from an URL.
I Created a service call rest.service.ts
rest.service.ts
import { Injectable } from '#angular/core';
import { HTTP } from '#ionic-native/http/ngx';
#Injectable({
providedIn: 'root'
})
export class RestService {
BASE_URL = 'http://whatever.....';
constructor(public http: HTTP) {}
getProjects() {
const URL = this.BASE_URL + 'getProjects';
this.http.get(URL, {}, { 'Content-Type': 'application/json' })
.then(answer => {
return JSON.parse(answer.data);
})
.catch(error => {
console.log(error.status);
console.log(error.error); // error message as string
console.log(error.headers);
});
}
}
Here in this file I can see the info. If I insert something like...
console.log(JSON.parse(answer.data));
I can see the results in JSON just as I Want.
The problem is when I try to use this methods in other files...
otherpage.page.ts
import { Platform } from '#ionic/angular';
import { RestService } from './../rest.service';
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-otherpage',
templateUrl: './otheropage .page.html',
styleUrls: ['./otherpage .page.scss']
})
export class OtherPage implements OnInit {
projects;
constructor(
public platform: Platform,
public rest: RestService,
) {
this.projects = this.rest.getProjects();
console.log(this.projects); // UNDEFINED
}
ngOnInit() { }
}
Here... this.projects... is undefined... ¿What is happening? I tried platform.ready, insert in ngOnInit... nothing works.
You need to modify the service and subscribe this service your page.
BASE_URL = 'http://whatever.....';
getProjects() {
const URL = this.BASE_URL + 'getProjects';
return this.http.get(URL, {}, { 'Content-Type': 'application/json' });
}
Subscribe this service observable in your page.ts file.
this.rest.getProjects().subscribe((answer)=>{
this.projects = JSON.parse(answer.data);
console.log(this.projects); // here you get the json
},error=>{
consoole.log(error)
});
Note:
console.log(this.projects); // UNDEFINED
Because this line executes before the http observable send the response, you need to subscribe that http observable to get the json.
I have .Net 4.6.2 VS 2017 Mvc application, with Angular 5, "rxjs": "^5.5.10"
I am trying to get data for Kendo UI grid through controller. The controller is returning data which I can see, but in the service class at code .map(response => response.json()), it says illegal return statement.(Please see attached image)
err img2
Here is vto.service.ts
import { Injectable } from '#angular/core';
import { VTO } from './vto';
import { Http, HttpModule, Headers, Response } from '#angular/http';
import { HttpClientModule, HttpClient, HttpHeaders} from '#angular/common/http';
import { Location, LocationStrategy, PathLocationStrategy } from '#angular/common';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
import {
toDataSourceRequestString,
translateDataSourceResultGroups,
translateAggregateResults,
DataResult,
DataSourceRequestState
} from '#progress/kendo-data-query';
import 'rxjs/add/operator/map';
import { GridDataResult, DataStateChangeEvent } from '#progress/kendo-angular-grid';
#Injectable()
export class Vtos {
// private vtoUrl = location.href.replace(location.hash, '') + '/home/GetVtos';
private vtoUrl = 'http://localhost:63213/Home/GetVtos';
constructor(private http: Http) { }
public getVtos(state: DataSourceRequestState): Observable<DataResult> {
const queryStr = `${toDataSourceRequestString(state)}`; //serialize the state
const hasGroups = state.group && state.group.length;
return this.http
.get(`${this.vtoUrl}?${queryStr}`) //send the state to the server
.map(response => response.json())
.map(({ data, total/*, aggregateResults*/ }) => // process the response
(<GridDataResult>{
//if there are groups convert them to compatible format
data: hasGroups ? translateDataSourceResultGroups(data) : data,
total: total,
// convert the aggregates if such exists
//aggregateResult: translateAggregateResults(aggregateResults)
}))
}
}
HomeController call to GetVots
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using VTO.DTO;
using VTO.DAL;
using Kendo.Mvc.UI;
using Kendo.Mvc.Extensions;
namespace VTO.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpGet]
public JsonResult GetVtos([DataSourceRequest]DataSourceRequest request)
{
return new JsonResult
{
ContentType = "application/json",
Data = Vto.GetVtos().ToDataSourceResult(request),
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
MaxJsonLength = int.MaxValue
};
}
}
A couple of observations here, this module is deprecated. See details here. Remove it from your app.
import { Http, HttpModule, Headers, Response } from '#angular/http';
You should use HttpClientModule,
import { HttpClient, HttpHeaders} from '#angular/common/http';
Keep it mind you have to import HttpClientModule on your app.module.ts (or any other module you have a dependency for it)
import { HttpClientModule } from '#angular/common/http';
Since HttpClientModule came into play. You not longer need for response.json(). Now HttpClient.get() returns an Observable of typed HttpResponse rather than just the JSON data. See docs. (vto.service.ts)
Remove,
.map(response => response.json())
Then you have,
constructor(private http: HttpClient) { }
public getVtos(state: DataSourceRequestState): Observable<DataResult> {
...
return this.http
.get(`${this.vtoUrl}?${queryStr}`)
.map(({ data, total/*, aggregateResults*/ }) =>
(<GridDataResult>{
data: hasGroups ? translateDataSourceResultGroups(data) : data,
total: total,
translateAggregateResults(aggregateResults)
}))
}
Sharing what worked for me. As Luillyfe mentioned Http is now deprecated, HttpClient is to be used. The returned response is already in Json, so no longer need to use .Json method.
constructor(private http: HttpClient) { }
public getVtos(state: DataSourceRequestState): Observable<DataResult> {
const queryStr = `${toDataSourceRequestString(state)}`; //serialize the state
const hasGroups = state.group && state.group.length;
return this.http
.get(`${this.vtoUrl}?${queryStr}`) //send the state to the server
.pipe(
map(<DataResult>({ Data, Total/*, aggregateResults*/ }) => {// process the response
console.log(Data);
return (<GridDataResult>{
data: hasGroups ? translateDataSourceResultGroups(Data) : Data.map(item => {
item.ReportDate = new Date(item.ReportDate); // convert to actual JavaScript date object
return item;
}),
total: Total
})
})
)
}
I am working on Angular 5 with Http.
Getting this error while serve the application..
import { Component, OnInit } from '#angular/core';
import { Router, ActivatedRoute, ParamMap } from '#angular/router';
import { HttpClient } from '#angular/common/http';
import 'rxjs/add/operator/switchMap';
#Component({
selector: 'app-post-detail',
templateUrl: './post-detail.component.html',
styleUrls: ['./post-detail.component.css']
})
export class PostDetailComponent implements OnInit {
body: string;
recent: {};
constructor(
private route: ActivatedRoute,
private router: Router,
private http: HttpClient,
) { }
ngOnInit() {
let id = this.route.snapshot.paramMap.get('id');
let userId = this.route.snapshot.paramMap.get('userid');
this.getUserPosts(userId);
this.http.get('https://jsonplaceholder.typicode.com/posts/'+id)
.subscribe((data)=>{
this.body = data.body;
});
}
}
I dont know Why I am getting this error and I assign the type as string in the class based on the syntax.
Response of API as below,
(data)=>{
this.body = data.body;
}
data is not json. You need to run .json() on data. Or you could run map before subscribe:
this.http.get('https://jsonplaceholder.typicode.com/posts/'+id)
.map(res => res.json())
.subscribe((data)=>{
this.body = data.body;
});
In order to use map, you need to import it:
import 'rxjs/add/operator/map'
See more examples here: https://angular.io/api/http/Http
EDIT:
The response is typed - you need to create an interface for the response:
interface SomeResponse {
Body: SomeType;
}
And make the request like this:
this.http.get<SomeResponse>'https://jsonplaceholder.typicode.com/posts/'+id)
.subscribe((data)=>{
this.body = data.body;
});
Again, more examples here: https://codingthesmartway.com/angular-4-3-httpclient-accessing-rest-web-services-with-angular/
This code works on angular2 v.2.0.0 .rc.2 but does't on angular2 v2.0.1
app.appcomponent.ts
import { Component, OnInit } from "#angular/core";
import { Injectable } from '#angular/core';
import { Http, Response, URLSearchParams } from "#angular/http";
import { IFood } from "./food";
import { Headers, RequestOptions } from "#angular/http";
I can import this for use .map right?
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/catch';
#Component({
selector: "my-app",
template: `
<h1>My First Angular 2 App</h1>
<ul *ngFor='let food of foods'>
<li>{{food.foodName}}</li>
</ul>
`,
templateUrl: "./app/form.html"
})
#Injectable()
export class AppComponent implements OnInit {
public values: string[];
public headers: Headers;
errorMessage: string;
I have a list of food in my controller, foodid, foodname
foods: IFood[];
foodModel = <IFood>{};
constructor(private http: Http) {
this.http = http;
this.headers = new Headers();
this.headers.append("Content-Type", "application/json");
}
ngOnInit() {
return this.http.get("/home/getdata")
there's .map does't work, can't we use .map in angular2 2.0.1?
.map((response: Response) => <IFood[]>response.json())
.subscribe(data => this.foods = data, error =>
this.errorMessage = <any>error);
}
}
Do I need to create Services?
How to fix this, thank you
Try updating to Typescript 2.0.3
This solved the issue for me.
And make sure you are using ECMAScript 6