Hello, There is a problem with a project that does not recognize a json file - and I do not know why. Is there anything I need to change or make it work?
this is my folders:
this is my service:
import { Injectable } from "#angular/core";
import { Ibrides } from "./brides";
import { HttpClient, HttpErrorResponse } from '#angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
#Injectable()
export class brideService {
private _brideUrl = 'api/brides.json';
constructor(private _http: HttpClient) { };
getBrides(): Observable<Ibrides[]> {
return this._http.get<Ibrides[]>(this._brideUrl)
.do(data => console.log('All:' + JSON.stringify(data)))
.catch(this.handleError)
}
private handleError(err: HttpErrorResponse) {
console.log(err.message);
return Observable.throw(err.message);
}
}
this is my component
import { Component, OnInit } from '#angular/core';
import { Ibrides } from "./brides";
import { brideService } from "./brides.service"
#Component({
selector: 'pm-brides',
templateUrl: './brides_list.component.html',
styleUrls: []
})
export class bridesListComponent implements OnInit {
constructor(private _brideService: brideService) {
}
errorMessage: string;
brides: Ibrides[] = [];
ngOnInit(): void {
this._brideService.getBrides()
.subscribe(brides => {
this.brides = brides
},
error => this.errorMessage = <any>error);
}
}
Just reference the file from the root level like this:
_brideUrl = 'app/api/brides.json'
For more information you can refer to this.
Related
I am working on a Contacts app with Angular 9. I get a list of contacts via the following service:
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { Contact } from '../models/Contact';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
}
#Injectable({
providedIn: 'root'
})
export class ContactsListService {
contactsUrl = 'https://randomuser.me/api/?&results=500&inc=name,location,email,cell,picture';
constructor(private http:HttpClient) { }
getContcts():Observable<Contact[]> {
return this.http.get<Contact[]>(`${this.contactsUrl}`);
}
}
The Contacts List component is as follows:
import { Component, OnInit } from '#angular/core';
import { from } from 'rxjs';
import { ContactsListService } from '../../services/contacts-list.service';
import { Contact } from '../../models/Contact';
#Component({
selector: 'app-list',
templateUrl: './list.component.html',
})
export class ListComponent implements OnInit {
contactsList:Contact[];
constructor(private ContactsListService:ContactsListService) { }
ngOnInit(): void {
this.ContactsListService.getContcts().subscribe(contactsList => {
this.contactsList = contactsList;
});
}
}
Trying to iterate the contacts list this way
<ul *ngFor="let contact of contactsList">
<li>{{contact.name.first}}</li>
</ul>
throws the error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
That very likely means contactsList is not an array.
What am I doing wrong?
The URL is returning an object of the form
{
results: [],
info: {}
}
Use RxJS map to map the results obtained from the API.
Service
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { pipe } from 'rxjs';
import { map } from 'rxjs/operators';
import { Contact } from '../models/Contact';
export class ContactsListService {
contactsUrl = 'https://randomuser.me/api/?&results=500&inc=name,location,email,cell,picture';
constructor(private http:HttpClient) { }
getContcts():Observable<Contact[]> {
return this.http.get<Contact[]>(`${this.contactsUrl}`)
.pipe(map(response => response['results']));
}
}
Assign empty array to contactsList on declaration.
Component
import { Component, OnInit } from '#angular/core';
import { from } from 'rxjs';
import { ContactsListService } from '../../services/contacts-list.service';
import { Contact } from '../../models/Contact';
#Component({
selector: 'app-list',
templateUrl: './list.component.html',
})
export class ListComponent implements OnInit {
contactsList: Contact[] = []; // assign empty array
constructor(private ContactsListService:ContactsListService) { }
ngOnInit(): void {
this.ContactsListService.getContcts().subscribe(
contactsList => { this.contactsList = contactsList; },
error => { // always good practice to handle error when subscribing to HTTP observables }
);
}
}
Seems like the endpoint 'https://randomuser.me/api/?&results=500&inc=name,location,email,cell,picture' does not return an array. To check it you may open it in the browser, or check in the network tab of the chrome developers tools while your app running
When i'm compile the angular code the compiler show me "Property 'push' does not exist on type 'any[]' " this error. Bellow the .service.ts and .component.ts code respectively.
Service.ts file
import { Injectable } from '#angular/core';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from '#angular/fire/firestore';
import { AngularFireDatabase} from 'angularfire2/database';
#Injectable({
providedIn: 'root'
})
export class UserService {
readonly userspath = "Development/users/users";
collectionRef= "Development"
ref = "Development"
usersRef="users"
public usersArray = [];
constructor(public af: AngularFireDatabase) { }
getUser(){
return this.af.database.ref(this.ref).child(this.usersRef)
}
}
component.ts file
import { Component, OnInit } from '#angular/core';
import { UserService } from '../services/user.service';
import { Router } from '#angular/router';
import { User } from '../models/user';
import { Observable } from 'rxjs';
#Component({
selector: 'app-employee',
templateUrl: './employee.component.html',
styleUrls: ['./employee.component.css']
})
export class EmployeeComponent implements OnInit {
public user = [];
usersArray = [];
constructor(
private userservice:UserService,
private router: Router
) { }
title = "Employees";
ngOnInit( ) {
this.userservice.getUser().on('value',snapshot => {
snapshot.forEach(data => {
this.usersArray.push(data.val());
})
})
}
VScode show me Property 'push' does not exist on type 'any[]' this error
Try This,
ngOnInit( ) {
this.userservice.getUser().on('value',snapshot => {
this.usersArray = [];
snapshot.forEach((data:any) => {
this.usersArray.push(data.val());
})
})
I have API for getting information about one specific restaurant in the database, but I have to get it with a POST request. I successfully get restaurantID from auth.service and another API when the restaurant is logged in, But when I tried to log restaurant in console, I get undefined. Uniformly I don't have permission to show API here. The code:
restaurant.service.ts
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Restaurant } from '../models/Restaurant';
import { LoggedRestaurant } from '../models/LoggedRestaurant';
import { AuthService } from './auth.service'
#Injectable({
providedIn: 'root'
})
export class RestaurantService {
private restaurantUrl = 'https://dm.dnevnimeni.com/dmnew/podacirestorana.php';
public restaurant: Restaurant;
public loggedRestaurant: LoggedRestaurant
public restaurantID = this.authService.currRestaurant[0].id
constructor(private http: HttpClient, private authService: AuthService) { }
getRestaurant(ID): Observable<LoggedRestaurant> {
console.log('ID je' + this.restaurantID);
return this.http.post<LoggedRestaurant>(this.restaurantUrl, ID);
}
}
informacije.component.ts
import { Component, OnInit } from '#angular/core';
import { AuthService } from '../services/auth.service';
import { RestaurantService } from '../services/restaurant.service';
import { Restaurant } from '../models/Restaurant';
import { LoggedRestaurant } from '../models/LoggedRestaurant';
import { Observable } from 'rxjs';
#Component({
selector: 'app-informacije',
templateUrl: './informacije.component.html',
styleUrls: ['./informacije.component.scss']
})
export class InformacijeComponent implements OnInit {
restaurant: Restaurant;
loggedRestaurant: LoggedRestaurant;
restaurantID = this.authService.currRestaurant[0].id;;
constructor(private restaurantService: RestaurantService, private authService: AuthService ) { }
getRestaurant() {
this.restaurantService.getRestaurant().subscribe(data => {
this.loggedRestaurant = data;
});
}
ngOnInit() {
this.getRestaurant();
this.restaurant = this.authService.currRestaurant[0];
console.log(this.restaurant)
console.log(this.loggedRestaurant)
this.restaurantID = this.restaurant.id;
console.log(this.restaurantID)
this.restaurantService.restaurantID =this.restaurantID;
}
}
Update
Your code should be like this
Since you just need to get data you dont have to use post
so you can change from this
return this.http.post<LoggedRestaurant>(this.restaurantUrl, this.restaurantID);
to this
return this.http.get<LoggedRestaurant>(`${this.restaurantUrl}/${this.restaurantID}`);
and add in ngOnInit
ngOnInit() {
this.restaurantService.getRestaurant().subscribe(data => {
this.loggedRestaurant = data;
// do something else
});
Because your getRestaurant() method is not called in ngOnInit life cycle hook so the data is not avaibled
You have a few issues with your code. First, you never actually call the getRestaurant() function, thus the service call will never be requested.
Second, you're dealing with asynchronous code and can't expect the service call to be complete before the console.log(this.loggedRestaurant) is run.
My suggestion is that you change your function to return an Observable<LoggedRestaurant> and subscribe to that.
getRestaurant(): Observable<LoggedRestaurant> {
this.restaurantService.getRestaurant().subscribe(data => {
this.loggedRestaurant = data;
});
}
Then you can use it as
ngOnInit() {
this.getRestaurant().subscribe(loggedRestaurant => {
console.log(loggedRestaurant);
});
}
Try this:
informacije.component.ts
import { Component, OnInit } from '#angular/core';
import { AuthService } from '../services/auth.service';
import { RestaurantService } from '../services/restaurant.service';
import { Restaurant } from '../models/Restaurant';
import { LoggedRestaurant } from '../models/LoggedRestaurant';
import { Observable } from 'rxjs';
#Component({
selector: 'app-informacije',
templateUrl: './informacije.component.html',
styleUrls: ['./informacije.component.scss']
})
export class InformacijeComponent implements OnInit {
restaurant: Restaurant;
loggedRestaurant: LoggedRestaurant;
restaurantID;
constructor(private restaurantService: RestaurantService, private authService: AuthService ) { }
getRestaurant() {
this.restaurantService.getRestaurant().subscribe(data => {
this.loggedRestaurant = data;
});
}
ngOnInit() {
this.getRestaurant(); // add this line
this.restaurant = this.authService.currRestaurant[0];
console.log(this.restaurant)
console.log(this.loggedRestaurant)
this.restaurantID = this.restaurant.id;
console.log(this.restaurantID)
this.restaurantService.restaurantID =this.restaurantID;
}
}
Hi i'm new in Angular 4 and I want to use it to build a WordPress theme using the wp-api. I start with the ng-wp-theme but I and all its working fine, but I need that hen a new post is publish the post list page updates itself without reload the page. I saw some tutorials about the http services in angular but I dont find any solution to this, maybe its a Wordpress api issue and not the Angular part.
here is the service:
import { Injectable } from '#angular/core';
import { HttpClient } from "#angular/common/http";
import { Observable } from 'rxjs/Observable';
import { Post } from './post';
import { environment } from '../../environments/environment';
#Injectable()
export class PostsService {
private _wpBase = environment.wpBase;
constructor(private http: HttpClient) { }
getPosts(): Observable<Post[]> {
return this.http.get<Post[]>(this._wpBase + 'posts');
}
getPost(slug: string): Observable<Post[]> {
return this.http.get<Post[]>(this._wpBase + `posts?slug=${slug}`);
}
}
and the controller:
import { Component, OnInit } from '#angular/core';
import { Post } from '../post';
import { PostsService } from '../posts.service';
import { Router } from '#angular/router';
import { HttpErrorResponse } from '#angular/common/http';
#Component({
selector: 'app-post-list',
templateUrl: './post-list.component.html',
styleUrls: ['./post-list.component.css'],
providers: [PostsService]
})
export class PostListComponent implements OnInit {
public posts: Post[];
constructor( private postsService: PostsService, private router: Router ) {}
ngOnInit() {
this.postsService.getPosts().subscribe(
(posts: Post[]) => this.posts = posts,
(err: HttpErrorResponse) => err.error instanceof Error ? console.log('An error occurred:', err.error.message) : console.log(`Backend returned code ${err.status}, body was: ${err.error}`));
}
selectPost(slug) {
this.router.navigate([slug]);
}
}
I am trying to display static JSON data in my angular 2 project. I am getting a console error 'GET http://localhost:4200/app/data/MOCK_DATA.json 404 (Not Found)' I have added my services.ts and component.ts pages.
service.ts
import { Injectable } from '#angular/core';
import { ConfigurationService } from '../../configuration.service';
import { Http, Response, RequestOptions, Headers } from '#angular/http';
import { Observable } from 'rxjs';
import { ListItem } from './list-item';
#Injectable()
export class DataService {
constructor(
private _http: Http,
private _configurationService: ConfigurationService
) {}
get() : Observable<ListItem[]> {
return this._http.get("app/data/MOCK_DATA.json")
.map((response: Response) => <ListItem[]> response.json())
}
}
app.component.ts
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import { DataService } from '../data.service';
import { ListItem } from './list-item';
import { Subscription } from 'rxjs';
#Component({
selector: 'app-component',
templateUrl: 'component.html',
styleUrls: ['component.css']
})
export class Component implements OnInit {
busy:Subscription;
datas: ListItem[] = [];
constructor(
private _dataService: DataService,
private _confirmationService: ConfirmationService,
private _authService: AuthService,
private _router: Router,
) {
}
ngOnInit(){
}
getdatas() {
this.busy =
this._dataService.get()
.subscribe(data => this.datas = data)
}
Since it is static. there is no need to http.get.
Create a json.ts file
export your JSON file as
export const json={
"key":"value"
}
then import it where required
import { json } from './json.ts'
then console.log(json) inside the class to check the file/json.