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.
Related
I have an application using laravel as backend and Angular in frontend.
What I want to do is to get the user data and output it anywhere on my website. For example I would like to get the name for the user and output it on the homepage when the user is logged in.
I can successfully register and log in a user. I can get the user data from my login method in the authService in the console.log. But how can I use that user data and get the user data from my getUser method? Is there any way for me to send the data from login method to the getUser method?
authService
import { Injectable } from '#angular/core';
import { User } from '../shared/user';
import { Observable, throwError } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { environment } from 'src/environments/environment';
import {
HttpClient,
HttpHeaders,
HttpErrorResponse
} from '#angular/common/http';
import { Router } from '#angular/router';
#Injectable({
providedIn: 'root'
})
export class AuthService {
endpoint: string = `${environment.RECIPE_LIST_API}`;
headers = new HttpHeaders().set('Content-Type', 'application/json');
currentUser = {};
constructor(private http: HttpClient, public router: Router) {}
// Log in
login(user: User) {
return this.http
.post<any>(`${this.endpoint}/login`, user)
.subscribe((res: any) => {
console.log(res);
localStorage.setItem('access_token', res.token);
this.currentUser = res;
});
}
getUser() {
this.currentUser
// want to get my userdata here so that I can send it to any component
}
}
component that I want to send my data to
import { Component, OnInit } from '#angular/core';
import { ActivatedRoute } from '#angular/router';
import { AuthService } from '../services/auth.service';
#Component({
selector: 'app-recipe-lists',
templateUrl: './recipe-lists.component.html',
styleUrls: ['./recipe-lists.component.css']
})
export class RecipeListsComponent implements OnInit {
currentUser: Object = {};
constructor(
public authService: AuthService,
private actRoute: ActivatedRoute
) {
this.authService.getUser();
}
ngOnInit(): void {}
}
user.ts
export class User {
email!: String;
password!: String;
}
How to re-fetch data after parameter change from:
oglas/1 to oglas/2 by click, so when put URL and than click ENTER everything works, but when click on oglas/2 button when oglas/1 is rendered URL changes to oglas/2 but data is from oglas/1?
TS
import { Component, OnInit } from "#angular/core";
import { ActivatedRoute } from "#angular/router";
import { Post } from "../post.model";
import { ServerService } from "../server.service";
#Component({
selector: "post",
templateUrl: "./post.component.html",
styleUrls: ["./post.component.css"]
})
export class PostComponent implements OnInit {
post: Post[];
constructor(
private route: ActivatedRoute,
private serverService: ServerService
) {}
ngOnInit(): void {
this.getPost();
}
getPost(): void {
const id = +this.route.snapshot.paramMap.get("id");
this.serverService.getPosts(id).subscribe(post => (this.post = post));
}
}
Service
import { HttpClient } from "#angular/common/http";
import { Injectable } from "#angular/core";
import { Post } from "./post.model";
import { User } from "./user.model";
import { Observable } from "rxjs";
#Injectable({ providedIn: "root" })
export class ServerService {
usersUrl = "http://localhost:3000/users";
postsUrl = "http://localhost:3000/posts";
constructor(private http: HttpClient) {}
getPosts(id: number | string): Observable<Post[]> {
const url = `${this.postsUrl}/${id}`;
return this.http.get<Post[]>(url);
}
getUser(id: number | string): Observable<User[]> {
const url = `${this.usersUrl}/${id}`;
return this.http.get<User[]>(url);
}
}
Since your are making an API call for data in ngOnInit(), requested data may not be available by the time your component loads. And Angular might be reusing the same instance of the component, making ngOnInit() to be called only once.
You can use Angular Resolvers to ensure that you have the required data before loading the component.
1) Create a route resolver to fetch the required data before loading the route.
PostDataResolver.ts:
// ... imports
#Injectable()
export class PostDataResolver implements Resolve<any> {
constructor(private serverService: ServerService) {}
resolve(route: ActivatedRouteSnapshot) {
const id = route.paramMap.get('id');
return this.serverService.getPosts(id);
}
}
2) Add this resolver to your routing module:
{ path: "oglas/:id", component: PostComponent, resolve: { postData: PostDataResolver }}
3) Then access the resolved data in your component.
PostComponent.ts:
export class PostComponent implements OnInit {
post: Post[];
constructor(
private route: ActivatedRoute,
private serverService: ServerService
) {}
ngOnInit(): void {
this.post = this.route.snapshot.data.postData;
}
}
This ensures that you have the latest and appropriate data before the component loads.
Got it...
import { Component, OnInit, OnChanges } from "#angular/core";
import { ActivatedRoute, Router } from "#angular/router";
import { Post } from "../post.model";
import { ServerService } from "../server.service";
#Component({
selector: "post",
templateUrl: "./post.component.html",
styleUrls: ["./post.component.css"]
})
export class PostComponent implements OnInit {
post: Post[];
id: number;
constructor(
private route: ActivatedRoute,
private serverService: ServerService
) {}
ngOnInit(): void {
this.route.paramMap.subscribe(params => {
this.id = parseInt(params.get("id"));
this.getPost(this.id);
});
}
getPost(id: number): void {
this.serverService.getPosts(id).subscribe(post => (this.post = post));
}
}
This code re-fetch data to a component
ngOnInit(): void {
this.route.paramMap.subscribe(params => {
this.id = parseInt(params.get("id"));
this.getPost(this.id);
});
}
Thank you all for your effort!
I am brand new to Angular and I am attempting to make a simple http request for data. How do I access this data in my component? I am getting the error 'Cannot read property 'get' of undefined'
data.service.ts
import { Injectable } from '#angular/core'
import { HttpClient } from '#angular/common/http'
#Injectable()
export class FetchData {
private url: string = 'https://jsonplaceholder.typicode.com/users'
constructor(private http: HttpClient){}
get(){
return this.http.get(this.url).subscribe(data => {
console.log(data)
})
}
}
table.component.ts
import { FetchData } from './datatable.service';
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-datatable',
templateUrl: './datatable.component.html',
styleUrls: ['./datatable.component.css']
})
export class DatatableComponent implements OnInit {
Data: FetchData
constructor() { }
ngOnInit() {
this.Data.get()
}
}
You need to "Inject" the service in your component and also make the subscription in your component.
In your service you should "map" your response.
import { Injectable } from '#angular/core'
import { HttpClient } from '#angular/common/http'
import 'rxjs/add/operator/map';
#Injectable()
export class FetchData {
private url: string = 'https://jsonplaceholder.typicode.com/users'
constructor(private http: HttpClient){}
get(){
return this.http.get(this.url).map(data => {
return data.json();
})
}
}
Your component:
import { FetchData } from './datatable.service';
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-datatable',
templateUrl: './datatable.component.html',
styleUrls: ['./datatable.component.css']
})
export class DatatableComponent implements OnInit {
constructor(private fetchDataService: FetchData) { }
ngOnInit() {
this.fetchDataService.get().subscribe(res => {
console.log(response);
});
}
}
try this:
export class DatatableComponent implements OnInit {
constructor(private dataService: FetchData) { }
ngOnInit() {
this.dataService.get()
}}
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.
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]);
}
}