I am using JSONPlaceholder to get data in service, but I am unable to get data at all. Please, help me out.
user.component.html
<p (click)="getUsers()">Click Me!</p>
<ul *ngFor="let x of users">
<li>{{x.name}}, {{x.age}}</li>
</ul>
user.component.ts
import { Component, OnInit } from '#angular/core';
import { Observable } from 'rxjs/Observable';
import { DataService } from '../../services/data.service';
import { Http } from '#angular/http';
#Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
constructor(private http:Http) { }
ngOnInit() {
}
getUsers(){
console.log(this.http.get("https://jsonplaceholder.typicode.com/posts"));
}
}
app.module.ts
//Basic File Inclusions
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
//Additional files inclusion
import { AppComponent } from './app.component';
import { UserComponent } from './components/user/user.component';
import { DataService } from './services/data.service';
import { Http } from '#angular/http';
#NgModule({
declarations: [
AppComponent,
UserComponent
],
imports: [
BrowserModule
],
providers: [ Http ],
bootstrap: [AppComponent]
})
export class AppModule { }
Please, can someone help me out making a successfull service call via http and get data on console.
Import
import { HttpModule } from '#angular/http';
in app.module.ts
imports: [HttpModule]
Rest of code will be same as you posted.
calling http like
this.http.get(`https://jsonplaceholder.typicode.com/posts`).subscribe(
data => {
console.log(data)
});
user.component.ts
import { Component, OnInit } from '#angular/core';
import { Observable } from 'rxjs/Observable';
import { DataService } from '../../services/data.service';
import { Http } from '#angular/http';
import { HttpClient } from '#angular/common/http';
#Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
constructor(private http: HttpClient) { }
ngOnInit() {
}
this.http.get(`https://jsonplaceholder.typicode.com/posts`).subscribe(
data => {
console.log(data)
});
}
app.module.ts
//Basic File Inclusions
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
//Additional files inclusion
import { AppComponent } from './app.component';
import { UserComponent } from './components/user/user.component';
import { DataService } from './services/data.service';
import { Http } from '#angular/http';
import { HttpModule } from "#angular/http";
#NgModule({
declarations: [
AppComponent,
UserComponent
],
imports: [
BrowserModule,
HttpModule
],
providers: [ Http ],
bootstrap: [AppComponent]
})
export class AppModule { }
Hope this may help you..
You are just calling http.get(url) and expecting something in return is like calling ajax method without success and error callback methods.
Kindly check Http documentation and usage of get and post methods
Mistake/Wrong Assumptions:
this.http.get(https://jsonplaceholder.typicode.com/posts) will not return http response which are expecting
Reality/Correct Approach:
You can use either pipe(can be used in the service) or subscribe(can be used in Component) method on http's get method whose return type is Observable.
Based on your requirement, you can use either of them
http.get('https://jsonplaceholder.typicode.com/posts')
// Call map on the response observable to get the parsed people object
.pipe(map(res => res.json()))
// Subscribe to the observable to get the parsed people object and attach it to the
// component
.subscribe(posts => this.posts = posts)
Hence your component code becomes:
user.component.ts
import { Component, OnInit } from '#angular/core';
import { Observable } from 'rxjs/Observable';
import { DataService } from '../../services/data.service';
import { Http } from '#angular/http';
#Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
constructor(private http:Http) { }
ngOnInit() {
}
getUsers(){
this.http.get("https://jsonplaceholder.typicode.com/posts")
.subscribe(posts=> console.log(posts))
}
}
Related
I want to display list of users using service use angular 8
data-service.service
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs' ;
import { HttpClientModule } from '#angular/common/http';
import 'rxjs/add/operator/map';
#Injectable({
providedIn: 'root'})
export class DataServiceService {
constructor(public http:HttpClientModule) {}
getPersone(){
return this.http.get('https://jsonplaceholder.typicode.com/users').map(res=>res.json);
}
}
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { FormsModule } from '#angular/Forms';
import {DataServiceService} from './services/data-service.service' ;
//import { HttpModule } from '#angular/Http';
import { HttpClientModule } from '#angular/common/http';
import { AppComponent } from './app.component';
import { NajibComponent } from './components/najib/najib.component';
import { EventsComponent } from './components/events/events.component';
import { CeventsComponent } from './components/cevents/cevents.component';
import { FormsComponent } from './components/forms/forms.component';
import { SComponentComponent } from './components/s-component/s-component.component';
import { from } from 'rxjs';
import { Server } from 'net';
#NgModule({
declarations: [
AppComponent,
NajibComponent,
EventsComponent,
CeventsComponent,
FormsComponent,
SComponentComponent
],
imports: [
BrowserModule,
FormsModule,
// HttpModule
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
s-component.component.ts
import { Component, OnInit } from '#angular/core';
import { DataServiceService } from '../../services/data-service.service';
#Component({
selector: 'app-s-component',
templateUrl: './s-component.component.html',
styleUrls: ['./s-component.component.css']
})
export class SComponentComponent implements OnInit {
users:any[]=[];
constructor(public dataService:DataServiceService) {
this.dataService.getPersone().subscribe(users=>{
this.users=users;
});
}
ngOnInit() {
}
}
s-component.component.html
<div class="container">
<p>s-component works!</p>
<ul >
<li *ngFor="let item of users">
{{ item.id }}
</li>
</ul>
</div>
You need to use constructor(private http: HttpClient)
In your DataServiceService:
import { HttpClient } from '#angular/common/http';
and inject same in constructor.
You should be injecting HttpClient to your service NOT the HttpClientModule in your DataServiceService.
First you need to import import { HttpClientModule } from '#angular/common/http'; in your main module you done that so now you need to in same module declare your service DataServiceService but in providers array.
Module:
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { DataService } from './shared/data.service';
import { HttpClientModule } from '#angular/common/http';
import { CComponentComponent } from './c-component/c-component.component';
#NgModule({
declarations: [
AppComponent,
CComponentComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
],
providers: [
DataService // < here is your own data service
],
bootstrap: [AppComponent]
})
export class AppModule { }
Service:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient) { }
getUsers() {
return this.http.get('https://jsonplaceholder.typicode.com/users')
}
}
component.ts:
import { Component, OnInit } from '#angular/core';
import { DataService } from '../shared/data.service';
import { Observable } from 'rxjs';
#Component({
selector: 'app-c-component',
templateUrl: './c-component.component.html',
styleUrls: ['./c-component.component.scss']
})
export class CComponentComponent implements OnInit {
users: Observable<any>
constructor(private data: DataService) { }
ngOnInit() {
this.users = this.data.getUsers()
}
}
component.html :
<div class="container">
<p>c-component works!</p>
<ul>
<li *ngFor="let user of users | async">
{{ user.id }}
</li>
</ul>
</div>
In your service you no need to call res.json If you really need response as a json. you can call it in your template like {{ user | json }} and it will display objects as a json file. As a response from http call in your service you getting an Observable<any> value. To ret rave data from that observable you need to subscribe to it or call pipe in your template like above users | async. This pipe will manage the subscription for you so you no need do that.
The following code is my viewall.ts code
import { Component, OnInit } from '#angular/core';
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Component({
selector: 'app-viewall',
templateUrl: './viewall.component.html',
styleUrls: ['./viewall.component.css']
})
#Injectable()
export class RestComponent {
constructor(private http: HttpClient) { }
configUrl = "http://34.201.147.118:3001/getAllData";
getConfig() {
return this.http.get(this.configUrl);
}
}
This is my app.module.ts code
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import {FormsModule} from'#angular/forms';
import { AppComponent } from './app.component';
import { RestComponent } from './rest/rest.component';
import { ViewallComponent } from './viewall/viewall.component';
import { HttpClientModule} from '#angular/common/http';
#NgModule({
declarations: [
AppComponent,
RestComponent,
ViewallComponent
],
imports: [
BrowserModule,FormsModule,
HttpClientModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
it is giving e the following error ERROR in src/app/app.module.ts(6,10): error TS2305: Module '"E:/paramount/paramount/src/app/viewall/viewall.component"' has no exported member 'ViewallComponent'.
Where is the exported class inside viewall.component.ts? You should be exporting a class from the component.
Haven't you declared RestComponent as Injectable and that too inside viewall.ts, and then you are importing it from rest.component file inside app.module.ts.
Try to move the RestComponent from the declarations array to providers array and also the import from the correct file.
Hope it helps.
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import {FormsModule} from'#angular/forms';
import { AppComponent } from './app.component';
import { RestComponent } from './rest/rest.component';
import { ViewallComponent } from './viewall/viewall.component';
import { HttpClientModule} from '#angular/common/http';
#NgModule({
declarations: [
AppComponent,
ViewallComponent
],
imports: [
BrowserModule,FormsModule,
HttpClientModule,
],
providers: [
RestComponent,
],
bootstrap: [AppComponent]
})
export class AppModule { }
Your viewall.component.ts should be exporting a class and look like this:-
import { Component, OnInit } from '#angular/core';
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Component({
selector: 'app-viewall',
templateUrl: './viewall.component.html',
styleUrls: ['./viewall.component.css']
})
export class ViewallComponent{}
injectable service is in providers
you can try with this solution.
providers: [
RestComponent,
],
declarations: [
AppComponent,
ViewallComponent
],
In viewall component.ts
import { Component, OnInit } from '#angular/core';
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Component({
selector: 'app-viewall',
templateUrl: './viewall.component.html',
styleUrls: ['./viewall.component.css']
})
export class ViewallComponent{
constructor() { }
}
#Injectable()
export class RestComponent {
constructor(private http: HttpClient) { }
configUrl = "http://34.201.147.118:3001/getAllData";
getConfig() {
return this.http.get(this.configUrl);
}
}
I got following error while retrieving a data from http://samples.openweathermap.org/data/2.5/history/city?q=Warren,OH&appid=b6907d289e10d714a6e88b30761fae22 in angular 5 service.
message: "Http failure response for (unknown url): 0 Unknown Error"
name: "HttpErrorResponse"
ok: false
status: 0
statusText: "Unknown Error"
While entering api URL directly on browser, it will return JSON object list.
Here is the code of my service weather.service.ts.
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http'
import 'rxjs/add/operator/map';
#Injectable()
export class WeatherService {
constructor(private _http: HttpClient) { }
dailyForecast() {
return this._http.get("http://samples.openweathermap.org/data/2.5/history/city?q=Warren,OH&appid=b6907d289e10d714a6e88b30761fae22")
.map(result => result);
}
}
Code on app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { HttpClientModule } from '#angular/common/http';
import { WeatherService } from './weather.service';
import { AppComponent } from './app.component';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [WeatherService],
bootstrap: [AppComponent]
})
export class AppModule { }
and code on app.component.ts
import { Component } from '#angular/core';
import { WeatherService } from './weather.service';
import { Chart } from 'chart.js';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private _weather: WeatherService) {}
ngOnInit() {
this._weather.dailyForecast()
.subscribe(res => {
console.log(res)
})
}
}
I cannot figure out what is going wrong on it.
It is a bug on HttpClient , you cannot fix otherwise use :
prefix stripping by using JSON.parse always.
It's CORS issue, please add header("Access-Control-Allow-Origin: *"); in your backend code.
When I am trying to use the service in my componenet and declatring it in constructor , I am getting this error TypeError: Cannot set property stack of [object Object] which has only a getter
I have below my code
import { Component } from '#angular/core';
import { FormBuilder,FormGroup} from '#angular/forms';
import { LoginService } from '../../services/login.service';
#Component({
selector: 'login-selector',
templateUrl: './app/components/login/login.component.html',
})
export class LoginComponent {
form:FormGroup;
items:Object;
constructor(
private formBuilder:FormBuilder,
private loginService:LoginService){
}
ngOnInit() {
this.form=this.formBuilder.group({
userName:this.formBuilder.control(''),
password:this.formBuilder.control(''),
remember:this.formBuilder.control(''),
textCaptcha:this.formBuilder.control('')
});
}
onSubmit(loginForm:FormGroup){
this.loginService.getTestJson().subscribe(mediaItems => {
this.items = mediaItems;
});
}
}
Service is
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class LoginService{
constructor(private http: Http) {}
getTestJson(){
return this.http.get('http://geo.groupkt.com/ip/172.217.3.14/json').map(response => {
return response.json();
});
}
}
and app module ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { ReactiveFormsModule } from '#angular/forms';
import { AppComponent } from './app.component';
import { LoginComponent } from './components/login/login.component';
import { LoginService } from './services/login.service';
#NgModule({
imports: [ BrowserModule,ReactiveFormsModule ],
declarations: [ AppComponent,LoginComponent ],
bootstrap: [ AppComponent ],
providers:[LoginService]
})
export class AppModule { }
import { HttpModule} from '#angular/http'; in app module ts
and add it in NgModule imports
It is likely you have ngModel in your Html, to do so, you need to be very careful.
You can't just use ngModel by itself in formGroup. It only works with formGroupName
I am trying to create a reusable component that serves as a processing overlay when making asynchronous calls across my site. I have a service in place but the OverlayComponent doesn't seem to get invoked when showOverlay is invoked:
app.module.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { HashLocationStrategy, LocationStrategy } from '#angular/common';
import { HttpModule } from '#angular/http';
import { AppRoutingModule } from './app-routing.module';
import { MainComponent } from './app.mysite.component';
import { OverlayComponent } from './app.mysite.overlay.component';
import { TrackerComponent } from './pages/tracker/mysite.tracker.component';
import { OverlayService } from "./overlay.service";
#NgModule({
imports: [ BrowserModule, AppRoutingModule, HttpModule ],
declarations: [
MainComponent,
OverlayComponent,
NavbarComponent,
TrackerComponent,
],
providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}, OverlayService],
bootstrap: [ MainComponent ]
})
export class AppModule { }
TrackerComponent.ts
import { Component, OnInit } from '#angular/core';
import { OverlayService } from '../../overlay.service.js';
#Component({
moduleId: module.id,
selector: 'tracker-component',
templateUrl: '/public/app/templates/pages/tracker/mysite.tracker.component.html',
providers: [ OverlayService]
})
export class TrackerComponent implements OnInit{
constructor(private http: Http, private overlayService: OverlayService) {
}
ngOnInit(): void {
this.overlayService.showOverlay('Processing...'); //This kicks everything off but doesn't show the alert or overlay
this.overlayService.test(); //does exactly what i'd expect
}
}
overlay.service.ts
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
#Injectable()
export class OverlayService {
private message: string;
private subject: Subject<any> = new Subject<any>();
showOverlay(msg: string) : void { //When this gets invoked, shouldn't it be invoking a change to this.subject and therefore invoking getMessage()
this.message = msg;
this.subject.next(msg);
}
getMessage(): Observable<any> {
return this.subject.asObservable();
}
test() {
return 'test good'; //if I call this function, it works
}
}
app.mysite.overlay.component
import { Component, OnInit } from '#angular/core';
import { OverlayService } from './overlay.service';
#Component({
selector: 'overlay-component',
templateUrl: '/public/app/templates/mysite.overlay.component.html',
styleUrls: ['public/app/scss/overlay.css'],
providers: [OverlayService]
})
export class OverlayComponent implements OnInit {
private processingMessage: string;
constructor(private overlayService: OverlayService) {}
ngOnInit() {
this.overlayService.getMessage().subscribe((message: string) => { //since i'm subscribed to this, i'm expecting this to get called. It doesn't
this.processingMessage = message;
alert(this.processingMessage); //never gets hit
$('.overlay-component-container').show(); // never gets hit
},
error => {
alert('error');
})
}
}
Specifying providers in the Component metadata actually creates a new injectable, scoped to that component tree.
If you want to share the overlay service across the app, you'll need to declare the overlay provider in the NgModule, and not in the components. Alternatively, you can declare it only as a provider on the top-level entry component (eg. AppComponent), though it may cause confusion when used in other entry components/lazy-loaded modules.
See https://angular.io/docs/ts/latest/guide/hierarchical-dependency-injection.html for a better explanation