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.
Related
In this Angular project which I am practicing through a tutorial,when I try to access pages that require authentication, I am redirected to login page and even the URL changes to http://localhost:4200/login?returnURL=%2Fcheck-out.
But after logging in ,it always redirects to home page irrespective of the links.
app.component.ts:
import { Component } from '#angular/core';
import { AuthService } from './auth.service';
import { Router } from '../../node_modules/#angular/router';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private auth:AuthService, router:Router){
auth.user$.subscribe(user=>{
if(user){
let returnUrl=localStorage.getItem('returnUrl');
router.navigateByUrl(returnUrl);
}
});
}
}
auth.service.ts:
import { Injectable } from '#angular/core';
import { AngularFireAuth } from '../../node_modules/angularfire2/auth';
import { Observable } from '../../node_modules/rxjs';
import * as firebase from 'firebase';
import { ActivatedRoute } from '../../node_modules/#angular/router';
#Injectable({
providedIn: 'root'
})
export class AuthService {
user$: Observable<firebase.User>;
constructor(private afAuth:AngularFireAuth,private route:ActivatedRoute) {
this.user$=afAuth.authState;
}
login(){
let returnUrl=this.route.snapshot.queryParamMap.get('returnUrl') ||'/';
localStorage.setItem('returnUrl',returnUrl);
this.afAuth.auth.signInWithRedirect(new firebase.auth.GoogleAuthProvider());
}
logout(){
this.afAuth.auth.signOut();
}
}
app.module.ts:
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import {AngularFireModule} from 'angularfire2';
import {AngularFireDatabaseModule} from 'angularfire2/database';
import {AngularFireAuthModule, AngularFireAuth} from 'angularfire2/auth';
import { Observable} from 'rxjs';
import {RouterModule, RouterOutlet, Routes} from '#angular/router';
import { AppComponent } from './app.component';
import { environment } from '../environments/environment';
import { BsNavbarComponent } from './bs-navbar/bs-navbar.component';
import { HomeComponent } from './home/home.component';
import { ProductsComponent } from './products/products.component';
import { ShoppingCartComponent } from './shopping-cart/shopping-cart.component';
import { CheckOutComponent } from './check-out/check-out.component';
import { OrderSucessfulComponent } from './order-sucessful/order-sucessful.component';
import { MyOrdersComponent } from './my-orders/my-orders.component';
import { AdminProductsComponent } from './admin/admin-products/admin-products.component';
import { AdminOrdersComponent } from './admin/admin-orders/admin-orders.component';
import { LoginComponent } from './login/login.component';
import {NgbModule} from '#ng-bootstrap/ng-bootstrap';
import { AuthService } from './auth.service';
import { AuthGuard } from './auth-guard.service';
export const appRoutes: Routes = [
{path:'',component:HomeComponent},
{path:'products',component:ProductsComponent},
{path:'shopping-cart',component:ShoppingCartComponent},
{path:'login',component:LoginComponent},
{path:'check-out',component:CheckOutComponent,canActivate:[AuthGuard]},
{path:'order-sucessful',component:OrderSucessfulComponent,canActivate:[AuthGuard]},
{path:'my/orders',component:MyOrdersComponent,canActivate:[AuthGuard]},
{path:'admin/products',component:AdminProductsComponent,canActivate:[AuthGuard]},
{path:'admin/orders',component:AdminOrdersComponent,canActivate:[AuthGuard]}
]
#NgModule({
declarations: [
AppComponent,
BsNavbarComponent,
HomeComponent,
ProductsComponent,
ShoppingCartComponent,
CheckOutComponent,
OrderSucessfulComponent,
MyOrdersComponent,
AdminProductsComponent,
AdminOrdersComponent,
LoginComponent
],
imports: [
BrowserModule,
RouterModule.forRoot(appRoutes),
AngularFireModule.initializeApp(environment.firebase),
AngularFireDatabaseModule,
AngularFireDatabaseModule,
NgbModule.forRoot()
],
providers: [AngularFireAuth,AuthService,AuthGuard],
bootstrap: [AppComponent]
})
export class AppModule { }
Seems to be in your localStorage.getItem('returnUrl'); always set to root of the application better to first check if there is a value and then remove that value and redirect the user like below:
let returnUrl = localStorage.getItem('returnUrl');
if (returnUrl) {
localStorage.removeItem('returnUrl');
router.navigateByUrl(returnUrl);
}
Hope this will helps you!
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 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))
}
}
I have trouble to direct an angular page to another component which i created. It should be directed to 'belize-local-time-component' when I click "take me back". But for right now, when I click "take me back", it directed to 'belize-local-time-component'page, but it did not stay, instead of coming back to the current page. Please help!! Thank you.
welcome-component.component.html
<p>
This is what I'm all about. <strong>Take me back</strong>.
</p>
welcome-component.component.ts
import { Component, OnInit } from '#angular/core';
import { ActivatedRoute } from '#angular/router';
import { Router } from '#angular/router';
#Component({
selector: 'app-welcome-component',
templateUrl: './welcome-component.component.html',
styleUrls: ['./welcome-component.component.css']
})
export class WelcomeComponentComponent implements OnInit {
constructor(private route: ActivatedRoute,private router: Router) {
this.route.params.subscribe(res => console.log(res.id));
}
ngOnInit() {
}
sendMeHome() {
this.router.navigate(['./belize-local-time-component']);
}
}
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
import { WelcomeComponentComponent } from './welcome-component/welcome-component.component';
import { BelizeLocalTimeComponentComponent } from './belize-local-time-component/belize-local-time-component.component';
import { AppRoutingModule } from './/app-routing.module';
import { FormsModule } from '#angular/forms';
import { Routes, RouterModule } from '#angular/router';
#NgModule({
declarations: [
AppComponent,
WelcomeComponentComponent,
BelizeLocalTimeComponentComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app-routing.module.ts
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { WelcomeComponentComponent} from './welcome-component/welcome-component.component';
import { BelizeLocalTimeComponentComponent } from './belize-local-time-component/belize-local-time-component.component';
import { Route } from '#angular/compiler/src/core';
import { Routes, RouterModule } from '#angular/router';
const routes: Routes = [
{
path: '',
component: WelcomeComponentComponent
},
{
path: 'belize-local-time-component',
component: BelizeLocalTimeComponentComponent
}
];
#NgModule({
imports:[RouterModule.forRoot(routes)],
exports:[RouterModule]
})
export class AppRoutingModule { }
The problem is with your anchor tag in Welcome component. You should remove href="" or use a button instead. Please check this sample that I have created for you:
https://stackblitz.com/edit/angular-yarabq
Swap the order of the paths in your routes.
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