I have node api that returns data to browser using this api :
app.get('/api/patients',function(req,res){
Patient.getPatients(function(err,patients){
if(err){
throw err;
}
console.log(patients.length);
res.json(patients);
});
});
I am trying to call this api from the service class.
import { Injectable } from '#angular/core';
import { Patient } from '../patient.interface';
#Injectable()
export class PatientDataService {
patients : Patient[] =[];
constructor() { }
getAllPatients(): Patient[]
{
// What to do here ??
}
}
How do i return data from node api to service ?
Use this
#Injectable()
export class PatientDataService {
patients : Patient[] =[];
constructor(private http:Http) { }
getAllPatients()
{
return this.http.get('base_url/api/people').map((res)=>res.json());
}
}
and in your component inject this service and call
this.patientService.getAllPatients().subscribe((data)=>{
//data is your patient list
})
You can first import the Angular2 Http library into your service:
import { Http } from '#angular/http';
I also import rx/js for use of Observables and mapping.
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
You can then inject the library into your service:
constructor(private _http: Http) { }
Make your http call to your node.js server like this:
getAllPatients(): Patient[]
{
// What to do here ??
return this._http.get('/api/patients')
.map(this.extractData)
.catch(this.handleError);
}
For more information, documentation, and clarification please read the Angular 2 Http Docs
Related
I wanna connect to the binance websocket api but I don't know how
I tried connecting to a specific url by making nestjs server a client but it doesn't console.log 'connected to the binance'
import { Injectable, OnModuleInit } from '#nestjs/common';
import { io, Socket } from 'socket.io-client'
#Injectable()
export class BinanceGateway implements OnModuleInit {
public binanceClient: Socket
constructor() {
this.binanceClient = io('https://api.binance.com')
}
onModuleInit() {
console.log('hello')
this.registerConsumerEvents()
}
registerConsumerEvents() {
this.binanceClient.on('connect', () => {
console.log('connected to the binance')
})
}
}
I find the solution to my question.
In order to access the binance websocket api with Nest.js, first, import binance-api-node :
const Binance = require('binance-api-node').default;
Then initialize it in the constructor of BinanceGateway class :
constructor() {
this.binanceClient = Binance()
}
Now you can get data from binanceClient; In my case I wanna get Candle Data So to get Candle Data :
this.binanceClient.ws.candles('ETHBTC', '1m', candle => {
console.log(candle)
})
Now, The final version of binance.gateway.ts is :
import { Injectable, OnModuleInit } from '#nestjs/common';
const Binance = require('binance-api-node').default;
#Injectable()
export class BinanceGateway implements OnModuleInit {
public binanceClient: any
constructor() {
this.binanceClient = Binance()
}
onModuleInit() {
console.log('hooooy')
this.binanceClient.ws.candles('ETHBTC', '1m', candle => {
console.log(candle)
})
}
}
I'm creating an Angular application connected to a Nodejs backend server. The Nodejs server response can be an array or Json object. I have to catch the correct data type according to the server response.
This is my Angular service code.
Note that my HttpClient functions return Json objects. Is there any function that returns any type of data?
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { map } from 'rxjs/operators'
import { City } from '../models/City';
import { Observable } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class CityService {
constructor(private http: HttpClient) { }
API_URI = 'http://localhost:5000'
getCities() {
return this.http.get(`${this.API_URI}/City`);
}
getCity(id: string) {
return this.http.get(`${this.API_URI}/City/${id}`);
}
deleteCity(id: string) {
return this.http.delete(`${this.API_URI}/City/${id}`);
}
saveCity(city: City) {
return this.http.post(`${this.API_URI}/City`, city);
}
updateCity(id: string|number|undefined, updatedCity: City): Observable<City> {
return this.http.put(`${this.API_URI}/City/${id}`, updatedCity);
}
}
Thanks a lot !
Check the returned type and transform the response in a map operator, you can then handle it accordingly in your subscribe
getCities() {
return this.http.get(`${this.API_URI}/City`).pipe(
map( body => {
return {
isArray: Array.isArray(body),
data: body
}
})
)
}
It's strange behavior for an API to return either an array or object (usually it's always one or the other). I suspect there may be something missing in your understanding/processing of the response, but I could be wrong😊
I have an async function getIdentByInfo and in the console i get the right output if i log it in this function. As soon as i call it in another component it doesnt work and i only get 'undefined'. I know it has something to do with beeing ssynchrone and Promises but i cant figure out how to solve my issue. I need the Model class filled with attributes coming from the http request in another component to send them to another service
import { EventEmitter, Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { IdentModel } from "../models/identmodel.model";
import { IdentteilComponent } from "../pages/identteil/identteil.component";
#Injectable({
providedIn: 'root',
})
export class InfoWebservice {
url = 'http://localhost:4201';
ident: IdentModel[];
constructor(private http: HttpClient) { }
// promise vom typ IdentModel zurückgeben
getIdentByInfo(id: string, vwk: string) {
this.http.get(this.url).toPromise().then(data => {
for (let i in data){
this.ident.push(data[i])
if ( this.ident[i].identNr == id && this.ident[i].vwk == vwk){
return this.ident[i];
}
}
});
}
}
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import { InfoWebservice } from '../../webservices/info.webservice'
import { ImageWebservice } from '../../webservices/image.webservice'
import { IdentModel } from "../../models/identmodel.model";
#Component({
selector: 'app-identteil',
templateUrl: './identteil.component.html',
styleUrls: ['./identteil.component.scss']
})
export class IdentteilComponent implements OnInit {
ident = [];
identNr:string;
vwk:string;
imgFrontLink:string;
imgBackLink:string;
constructor(private router: Router, private service: InfoWebservice, private image: ImageWebservice) { }
getIdentNr() : string {
var split = this.router.url.split("/");
this.identNr = split[2];
return this.identNr;
}
//return type is STRING
getVwk() {
// output von window.location.host = repapp-maw.dbl.de
// var splitHost = window.location.host.split(".");
var splitHost = 'repapp-maw';
var splitV = splitHost.split("-");
this.vwk = splitV[1];
return this.vwk;
}
callInfoService = async () => {
return await this.service.getIdentByInfo(this.getIdentNr(), this.getVwk());
}
ngOnInit() {
console.log(this.callInfoService());
}
}
When you use angular, its always preferred not to use await/Promise. Angular has an in-built RX-JS library which has tonnes of super-awesome functionalities that you can use.
For Example, in your case, you can do something like this:
// Your Service File can make use of 'Behavior Subject'
// Please read more about it here: https://www.learnrxjs.io/learn-rxjs/subjects/behaviorsubject
import { EventEmitter, Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { IdentModel } from "../models/identmodel.model";
import { IdentteilComponent } from "../pages/identteil/identteil.component";
#Injectable({
providedIn: 'root',
})
export class InfoWebservice {
url = 'http://localhost:4201';
ident: IdentModel[];
initialIdentValues: IdentModel = [];
private identSource: BehaviorSubject<IdentModel[]> = new BehaviorSubject<IdentModel[]>(this.initialIdentValues);
public identValuesObs$: Observable<IdentModel[]> = this.identSource.asObservable();
// Create a method to set the values in component-1
setIdentValues(identValues: IdentModel[]) {
this.identSource.next(identValues);
}
// Create a method to return values in component-2 or any component
returnIdentValues() {
return this.identValuesObs$;
}
constructor(private http: HttpClient) { }
// Change your service call to this:
getIdentByInfo(id: string, vwk: string): Observable<any> {
return this.http.get(this.url);
}
}
Now in your component-1 where you want to set the values of this identvalues:
// Component-1
constructor(private infoWebService: InfoWebService){}
// Create a method where you get the values
someMethod() {
// Call the API method here and subscribe and then set the values
this.infoWebService.getIdentInfoById(id, vwk).subscribe((data: any) => {
// Your logic goes here ANDD
if (data) {
for (let i in data){
this.ident.push(data[i])
let localIdentsWithRequiredLogic = [];
if ( this.ident[i].identNr == id && this.ident[i].vwk == vwk){
localIdentsWithRequiredLogic.push(this.ident[i]);
}
// THIS IS IMPORTANT
this.infoWebService.setIdentValues(localIdentsWithRequiredLogic);
}
}
})
}
Then in component-2 or whatever component you want, you can retrieve it using the returnIdentValues method like this:
// In component-2
inSomeMethodWhereYouRequireIdentValues() {
this.infoWebService.returnIdentValues().subscribe(data => {
console.log(data) // this is data that you set in component one
})
}
i make news application with news api and i fetch data properly and but not sending data from service to component so how can send data from service to component
and component to component through rxjs
import { Injectable } from '#angular/core';
import { Subject } from 'rxjs';
#Injectable()
export class NewService {
private pushSource = new Subject<object>();
Country_Name;
constructor(private http:HttpClient,) {
this.messages$ = this.pushSource.asObservable()
} // define function for call the category
categoryNews(category)
{
var categoryData = this.http.get(`https://newsapi.org/v2/top-headlines?country=in&category=${category}&apiKey=********`)
.subscribe(Data=> this.pushSource.next(Data));
}
news(t_h)
{
console.log(t_h);
this.pushSource.next(t_h);
} }
here is you not import Observable, observable that's why the problem occurred
import { Injectable } from '#angular/core';
import { Subject, Observable, observable } from 'rxjs';
#Injectable()
export class NewService {
messages$: Observable;
private pushSource = new Subject();
Country_Name;
constructor(private http:HttpClient,) {
this.messages$ = this.pushSource.asObservable()
}
categoryNews(category)
{
var categoryData = this.http.get(https://newsapi.org/v2/top-headlines?country=in&category=${category}&apiKey=*****)
categoryData.subscribe(Data=> this.pushSource.next(Data));
}
news(t_h)
{
console.log(t_h);
this.pushSource.next(t_h);
}
I'm building a school project using angular js and node js as a backend, I'm trying to display the event in my front-end using Angular JS from EventBrite, After spending a few hours checking different tutorial I wrote this code
Node JS code:
router.get('/', (req, res)=>{
axios.get(`${EventsBriteAPI}`).then(result=>{
let relevantData = result.data.data.events
res.status(200).json(relevantData);
console.log(results );
})
.catch(error => {
res.status(500).send(error);
})
});
My service code:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class EventsService {
uri = 'http://localhost:4600/events';
constructor(private httpClient: HttpClient) {}
getAllEvents(){
return this.httpClient.get(this.uri);
}
}
My component code
import { Component } from '#angular/core';
import { EventsService } from './events.service';
import { Observable } from 'rxjs/internal/Observable';
#Component({
selector: 'events',
templateUrl: 'events.Component.html'
})
export class EventsComponent {
title = "List of events";
eventObservable : Observable<any[]> ;
constructor(service: EventsService){
this.eventObservable = service.getAllEvents();
console.log(this.eventObservable);
}
}
When I'm running my code I'm getting this error
src/app/component/events/events.component.ts(21,5): error TS2322: Type 'Observable' is not assignable to type 'Observable'.
The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?
Type 'Object' is missing the following properties from type 'any[]': length, pop, push, concat, and 26 more. and It's not displaying anything in my front-end
Could you please help me with that.
we don't need to use Observable type variable unless you are using async pipe or for any specific requirement.
You can do some like below,
EventsComponent.ts
eventObservable: any = [];
constructor(private service: EventsService) {
this.service.getAllEvents().subscribe((response: any) =>{
this.eventObservable = response;
console.log(this.eventObservable);
});
}
we generally use ngOnInit() for calling an api data not in the constructor().