How to convert the value stored in Observable<any> to a string, in typescript? - json

Hi I am new to Angular and TypeScript. I need the value of an Observable in the format of a string, how does one do this?
the BmxComponent file
export class BmxComponent {
asyncString = this.httpService.getDataBmx();
currentStock = this.httpService.getDataBmx2(); //this is what I want to covert to a string so I can pass it to onSubmit()
onSubmit() {
const asnNumm = this.currentStock; // passing it here changes my database, see below
this.httpService.sendData({ stock: asnNumm })
.subscribe(
data => console.log(data),
error => console.log(error)
);
}
}
the HttpService file
export class HttpService {
constructor(private http: Http) {}
getDataBmx() {
return this.http.get('https://the-bicycle-shop.firebaseio.com/products/Bicycles/bmx/stock.json')
.map((response: Response) => response.json());
}
getDataBmx2() {
return (this.http.get('https://the-bicycle-shop.firebaseio.com/products/Bicycles/bmx/stock.json'));
}
sendData(newStock: any) {
const body = JSON.stringify(newStock);
const headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.patch('https://the-bicycle-shop.firebaseio.com/products/Bicycles/bmx.json', body, {
headers: headers
})
.map((data: Response) => data.json())
.catch(this.handleError);
}
private handleError(error: any) {
console.log(error);
return Observable.throw(error.json());
}
}
the html file
<p>{{asyncString | async}}</p> // displays 1234 which is the correct value
<p>{{asyncString}}</p> // displays [object Object]
<p>{{currentStock}}</p> // displays [object Object]
<button class="btn btn-success" (click)="onSubmit()">Change Database</button>
my database before onSubmit() (used when I click the Change Database button)
Bicycles
|
---bmx
|
---stock = 1234;
my database after onSubmit()
Bicycles
|
--- bmx
|
---stock
|
--- _isScalar = false
I am using Firebase for this.
I know it will work with a string because I tested it with like this:
onSubmit() {
const asnNumm = "33333" //the change to test it
this.httpService.sendData({ stock: asnNumm })
.subscribe(
data => console.log(data),
error => console.log(error)
);
}
Which does this to my database
Bicycles
|
---bmx
|
---stock = 33333
I understand that currentStock would hold the same value that is currently stored in my database, so it would make no difference, but I want to change it once I have converted it to a string.
Basically I want to change "stock" in my database, but by a fixed amount each time I press the Change Database button, for example, minus 1 it each time it is pressed.

Subscribe to the observable to get the result and call onSubmit when you receive the value:
currentStock = this.httpService.getDataBmx2()
.subscribe(val => this.onSubmit(val));

Objects has toString method that you can implement to show the value of object, or convert it to string with JSON.stringify() like this
this.httpService.sendData({ stock: asnNumm })
.subscribe(
data => console.log(JSON.stringify(data)),
error => console.log(error)
);
You have to map to the response object to get data, to get data as text you can query response object
getDataBmx2() {
return this.http.get('https://the-bicycle-shop.firebaseio.com/products/Bicycles/bmx/stock.json')
.map((response: Response) => response.text());
}
export class BmxComponent {
currentStock: string;
this.httpService.getDataBmx2().subscribe(s => this.currentStock = s); //this is what I want to covert to a string so I can pass it to onSubmit()
onSubmit() {
const asnNumm = this.currentStock; // passing it here changes my database, see below

Related

How to convert json to JSONP after it json load as a subscription in angular?

I want to make a call with jsonp but i have json data as a subscription
my service.ts file:-
gridUrl = 'https://jsonplaceholder.typicode.com/posts';
getGrid() {
return this.http.get<Grid>(this.gridUrl, httpOptions);
}
and in my component.ts
grid: Grid;
grids: any;
showGrid() {
this.gridService.getGrid()
.subscribe(
gridData => this.grids = gridData
);
}
That above code is working fine and gives me data in grids variable as a json
But I need to use that json data in below code .
private fetch(action: string = '', data?: any): Observable<any[]> {
return this.http
.jsonp(`https://jsonplaceholder.typicode.com/posts/${action}?${this.serializeModels(data)}`, 'callback')
.pipe(map(res => <any[]>res));
}
How would I do that?

display data from json object on HTML in angular 5

hello i want to display the data that i got from a mongodb using a backend api (nodejs)
this is the code for event model
const mongoose = require('mongoose');
const config = require('../config/database');
// Events Schema
const EventSchema = mongoose.Schema({
eventname: {
type: String,
required: true
},
eventstartdate: {
type: String,
required: true
},
eventenddate: {
type: String,
required: true
},
eventcategorie: {
type: String
},
eventdescription: {
type: String
},
eventimage: {
type: String
}
});
const Event = module.exports = mongoose.model('Event', EventSchema);
this is the code from the router
const express = require('express');
const router = express.Router();
const passport = require('passport');
const jwt = require('jsonwebtoken');
const config = require ('../config/database');
const User = require('../models/user');
const Event = require('../models/event');
//get event by id
router.get('/event/:eventid', (req,res) => {
Event.findById(req.params.eventid, (err, event) =>{
if (err){
return res.status(500).send({message:err.message});
}
if(!event){
return res.status(400).send({message:'Event not found'});
}
res.json({
event: {
id: event._id,
eventname: event.eventname,
eventstartdate: event.eventstartdate,
eventenddate: event.eventenddate,
eventcategorie: event.eventcategorie,
eventdescription: event.eventdescription,
eventimage: event.eventimage
}
});
});
});
and this is the code from the service in the angular
// GET an event by ID
displayEvent$(id: string) {
return this.http.get(`http://localhost:3000/users/event/${id}`)
.map(response => response.json());
}
then i created a simple method that is triggered by a button
and i passed an id of an event that i konw is in the database just to test it out
onclickeventpage(){
this.authService.displayEvent$('5ae0c8e96b40a71cd3b772cc').subscribe(event => {
console.log(event)
});
}
this gives me back at the console the event i need with every aribute
but whene i change this
console.log(event)
to this so i can get evey atribute separetly and then i an put them in the html
console.log(event.eventname)
i get undefined
i just want to know how to get every event atribute so i can display them in my html page
First you dont have to call .json() witn angular5
displayEvent$(id: string) {
return this.http.get(`http://localhost:3000/users/event/${id}`)
.map(response => response.json());
}
also you need to access
console.log(event.event.eventname);
HttpModule is deprecated and the new HttpClientModule by default formats the response to JSON so we no longer need to parse it using response.json():
I just want to know how to get every event attribute so that I can
display them on my HTML page
You can tell HttpClient the type of the response to make consuming the output easier and more obvious.
Typechecking of response can be done by using type parameter
export interface Ievent {
id:string
eventname: string
eventstartdate: string
eventenddate: string
eventcategorie: string
eventdescription: string
eventimage: string
}
Http returns an observable and We can tell the HttpClient.get to return response as Ievent type When we use http.get<Ievent>(...) then it returns the instance of Observable<Ievent> type.
In your service
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs/Observable';
import {Ievent} from './eventModel'
#Injectable()
export class authService()
{
constructor(private http:HttpClient){}
displayEvent$(id: string)Observable<Ievent> {
return this.http.get<Ievent>(`http://localhost:3000/users/event/${id}`);
}
}
In your component subscribe to Observable<Ievent> to get instance of Ievent
onclickeventpage(){
this.authService.displayEvent$('5ae0c8e96b40a71cd3b772cc').subscribe(event => {
console.log(event);
console.log(event.eventname)});
}

Angular: Typescript casting JSON response as object model not working

I have an issue while I try to cast a json response to object, all the properties of my object are string is that normal ?
Here is my ajax request :
public getSingle = (keys: any[]): Observable<Badge> => {
return this._http.get(this.actionUrl + this.getKeysUrl(keys))
.map((response: Response) => response.json() as Badge )
.catch(this.handleError);
}
Here is my badge model :
export interface Badge {
badgeNumber: number;
authorizationLevel: number;
endOfValidity: Date;
}
And here is where I call the service function and I'm facing the issue :
this._badgeService.getSingle(this.ids).subscribe(
(badge: Badge) => {
console.log(typeof(badge.endOfValidity)); // <-- returning string and not Date
},
error => console.log(error);
});
Thats kinda tricky to explain:
Date is a class, this means that values of type Date need to be created through a constructor call. In other words, create a class instance with new Date(...).
The Response.json method will only return an object in JSON format, and such doesnt contain an instance of any class, only maps of key:property.
So what you need to do, is to manually convert the value returned from .json() to a Base object. This can be done as follows:
public getSingle = (keys: any[]): Observable<Badge> => {
return this._http.get(this.actionUrl + this.getKeysUrl(keys))
.map(r => r.json())
.map(v => <Badge>{
badgeNumber: v.badgeNumber,
authorizationLevel: v.authorizationLevel,
endOfValidity: new Date(v.endOfValidity)
// preferably this string should be in ISO-8601 format
})
//the mapping step can be done in other ways most likely
.catch(this.handleError);
}

How to map a JSON string into a TypeScript (JavaScript) object in AngularJS 2?

Consider this simple snippet of an AngularJS 2 application:
TestObject
export class TestObject {
id: number;
name: string;
}
TestService
[...]
export class TestService {
constructor(private http: Http) {}
test(): Observable<TestObject> {
return this.http
.get("http://www.example.com")
.map(this.save)
.catch(this.fail);
}
private save(response: Response) {
let testObject: TestObject = <TestObject> response.json();
return testObject || {};
}
private fail(error: any) {
return Observable.throw("error!");
}
}
AppComponent
[...]
export class AppComponent implements OnInit {
testObject: TestObject;
constructor(private testService: testService) {}
ngOnInit() {
this.testService.test().subscribe(
data => {
this.testObject = new TestObject();
console.log(this.testObject); // prints (empty) TestObject
this.testObject = data;
console.log(this.testObject); // prints object, not TestObject?
},
error => { }
);
}
}
Here my questions:
1) Why does my application print out (using Chrome Inspector) object and not TestObject as type?
2) The property testObject of class AppComponent should be of type TestObject. Why does my application not fail?
3) How can I achieve that I really get TestObject? What would be the best way to do it? Of course I could just manually fill up my TestObject, but I hoped there is some way of automatically mapping the json to my object.
Here is an answer that I wrote to a question which explained the handling of observables in angular2.
Angular 2 http post is returning 200 but no response is returned
Here you can see how I am handling the Response object as returned by the service. It is very important that you return your response object from the map function in service.
Similarly you can convert your response object to typescript type by casting your response object. The example can be:
this._loginService.login(this.username, this.password)
.subscribe(
(response) => {
//Here you can map the response to a type.
this.apiResult = <IUser>response.json();
//You cannot log your object here. Here you can only map.
},
(err) => {
//Here you can catch the error
},
() => {
//this is fired after the api requeest is completed.
//here you can log your object.
console.log(this.apiResult);
//result will only be shown here.
}
);
Here, it can be clearly seen that I am casting the response object to IUser type.
Another thing is while handling apiresponse in your component it is to be noted that the subscribe function has three arguments and if you will like to log your object, you must do it in the last function of subscribe.
Hope this helps!
your call must be like
ngOnInit() {
this.testService.test().subscribe(
(data) => {
this.testObject = new TestObject();
console.log(this.testObject); // prints (empty) TestObject
//only mapping
this.testObject = data;
},
error => { },
() => {
console.log(this.testObject);
}
);
}

Failing to parse response json into an object with Angular2

I am trying to follow these directions: https://angular.io/docs/ts/latest/guide/server-communication.html and get the list of objects from the server in form of an object (not json).
I have a model class (simplified for now):
export class Goal {
id: number;
title: string;
}
And I am trying to get list of these from the server through a service class as follows:
export class GoalsService {
constructor(public authHttp:AuthHttp) {
}
getGoals() {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.authHttp.get('<%= BACKEND_BASE_URL %>' + '/rrm/api/v1/goals', options)
.map(res => {
<Goal[]> res.json()
}
)
.do(data => console.log(data))
.catch(this.handleError);
}
...
And the client using the service class is:
loadGoals() {
this.goalsService.getGoals().subscribe(
goals => this.goals = goals
);
}
The request goes through properly and I am getting back:
[{"id":1,"title":"target"}]
However, in the client, inside subscribe, goals variable is always 'undefined'.
I tried debugging it, this is what I get:
Which says to me that json received and parsed properly, but casting it into a target object is not working (unless I am not fully getting the mechanism).
What am I doing wrong?
Thanks,
Note: the authHttp service that I use is this guy: https://auth0.com/blog/2015/11/10/introducing-angular2-jwt-a-library-for-angular2-authentication/. And it works in all other places as expected. So I doubt that it is a peoblem.
As you are using map arrow function, you should return mapped result.
return this.authHttp.get('<%= BACKEND_BASE_URL %>' + '/rrm/api/v1/goals', options)
.map(res => {
return <Goal[]> res.json(); //return mapped object from here
}
)
OR
return this.authHttp.get('<%= BACKEND_BASE_URL %>' + '/rrm/api/v1/goals', options)
.map(res => <Goal[]> res.json()) //or simply do map object directly