Trying to load local json file in Angular8 - angular8

I'm trying to load local json file but I keep getting an error:
import { Injectable } from "#angular/core";
import { HttpClient } from "#angular/common/http";
#Injectable({
providedIn: "root"
})
export class SearchService {
constructor(private http: HttpClient) {}
getJsonFIle() {
this.http.get("./configs/dor.json").subscribe(data => {
console.log(data);
});
}
}
This is the error on the browser:

Related

ngx-toastr.js?4996:264 Uncaught TypeError: Object(...) is not a function at eval (ngx-toastr.js?4996:264)

I am using ngx-toastr in angular 6 for http error notification, as injected ToastrService in httpInterceptor
export class MyInterceptor implements HttpInterceptor {
constructor(public toasterService: ToastrService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request)
.pipe(
tap((evt: any) => {
if (evt instanceof HttpResponse) {
if (evt.body)
this.toasterService.success('success', '!!', { positionClass: 'toast-bottom-center' });
//alert(`success`);
}
}),
catchError((err: any) => {
if (err instanceof HttpErrorResponse) {
try {
this.toasterService.error(err.error.message, err.error.title, { positionClass: 'toast-bottom-center' });
} catch (e) {
this.toasterService.error('An error occurred', '', { positionClass: 'toast-bottom-center' });
}
//log error
}
return of(err);
})
)
}
}
and imported ToastrModule in app.module.ts like
imports:[
ToastrModule.forRoot()
]
I am getting below error, any idea whats going wrong here..............
ngx-toastr.js?4996:264 Uncaught TypeError: Object(...) is not a
function
at eval (ngx-toastr.js?4996:264) .................................
I found the actual issue regarding this. It's happening because of the mismatch of the version of an angular and the package. To overcome this problem perform the following steps
STEP1: Check for angular CLI version: ng --version
Now check this image
If your angular version is 7.3.10 then you need to install 10.1.0 version of ngx-toastr
STEP2: Install a specific version of ngx-toastr according to your angular CLI version: npm i ngx-toastr#10.1.0 --save
STEP3: import it into app.module.ts
app.module.ts
import { CommonModule } from '#angular/common';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations';
import { ToastrModule } from 'ngx-toastr';
#NgModule({
imports: [
CommonModule,
BrowserAnimationsModule, // required animations module
ToastrModule.forRoot() // ToastrModule added
],
bootstrap: [App],
declarations: [App]
})
export class AppModule {}
STEP4: add css path in styles array in angular.json file
angular.json
"styles": [
"node_modules/font-awesome/css/font-awesome.css",
"src/styles/app.scss",
"node_modules/sweetalert2/dist/sweetalert2.min.css",
"node_modules/ngx-toastr/toastr.css"
]
Don't forget to restart your server after making changes in angular.json file
STEP5: make helper service to show toasters
helper.service.ts
import { Injectable } from '#angular/core';
import { ToastrService } from 'ngx-toastr';
#Injectable({
providedIn: 'root'
})
export class HelperService {
constructor(private toastr: ToastrService) { };
showSuccessToast(msg) {
this.toastr.success(msg);
}
showErrorToast(msg) {
this.toastr.error(msg);
}
showInfoToast(msg) {
this.toastr.info(msg);
}
}
STEP6: Now you are done you just need to use these functions in your component.ts file
user.component.ts
import { Component, OnInit } from '#angular/core';
import { routerTransition } from '../../router.animations';
import { UserService } from './user.service';
import { HelperService } from 'src/app/helpers/helper.service';
#Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.scss'],
animations: [routerTransition()]
})
export class UserComponent implements OnInit {
constructor(
private userService: UserService,
private helperService: HelperService,
) {
}
ngOnInit() {
this.getUsers();
}
async getUsers() {
try {
const res: any = await this.userService.getUsers();
this.helperService.showSuccessToast(res.message);
} catch (err) {
this.helperService.showErrorToast(err.error || 'Something went wrong');
}
}
}

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked in HTTP loading interceptor

Goal:
Im trying to show a loading icon on every ajax call.To this end, I added an HTTP interceptor which sets a variable to true when one or more requests are ongoing and to false when all have completed. The UI tests for this value and shows a loader or not, depending.
Problem:
On every ajax call, an error is thrown:
ExpressionChangedAfterItHasBeenCheckedError:
Expression has changed after it was checked.
Previous value: 'ngIf: [object Object]'. Current value: 'ngIf: true'.
Simplified Stakckblitz with reproducible error:
https://stackblitz.com/edit/angular-h4rpfb
Code:
appcomponent.html:
<p *ngIf="loaderService.isLoading | async">
Loading!
</p>
<p *ngIf="!(loaderService.isLoading | async)">
Not Loading!
</p>
<button (click)="loadSomething()">Load Something</button>
{{matches|async}}
appcomponent.ts:
import { Component } from "#angular/core";
import { HttpClient } from "#angular/common/http";
import { LoaderService } from "./core";
import { Observable } from "rxjs";
#Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
matches: Observable<any>;
constructor(public loaderService: LoaderService, private http: HttpClient) {}
loadSomething() {
this.matches = this.http.get("https://jsonplaceholder.typicode.com/posts");
}
}
loader.interceptor.ts:
import { Injectable } from '#angular/core';
import {
HttpErrorResponse,
HttpResponse,
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '#angular/common/http';
import { Observable } from 'rxjs/Observable';
import { LoaderService } from './loader.service';
#Injectable()
export class LoaderInterceptor implements HttpInterceptor {
private requests: HttpRequest<any>[] = [];
constructor(private loaderService: LoaderService) { }
removeRequest(req: HttpRequest<any>) {
const i = this.requests.indexOf(req);
if (i >= 0) {
this.requests.splice(i, 1);
}
console.log(i, this.requests.length);
this.loaderService.isLoading.next(this.requests.length > 0);
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.requests.push(req);
this.loaderService.isLoading.next(true);
return Observable.create(observer => {
const subscription = next.handle(req)
.subscribe(
event => {
if (event instanceof HttpResponse) {
this.removeRequest(req);
observer.next(event);
}
},
err => { this.removeRequest(req); observer.error(err); },
() => { this.removeRequest(req); observer.complete(); });
// teardown logic in case of cancelled requests
return () => {
this.removeRequest(req);
subscription.unsubscribe();
};
});
}
}
loader.service.ts:
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs/Observable';
import { ReplaySubject } from 'rxjs/ReplaySubject';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
#Injectable()
export class LoaderService {
public isLoading = new BehaviorSubject(false);
constructor() {}
}
Ok I got it to work by adding this to the component with the loader:
changeDetection: ChangeDetectionStrategy.OnPush
So the appcomponent.html now looks like this:
import { Component,ChangeDetectionStrategy } from "#angular/core";
import { HttpClient } from "#angular/common/http";
import { LoaderService } from "./core";
import { Observable } from "rxjs";
#Component({
changeDetection: ChangeDetectionStrategy.OnPush,
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
matches: Observable<any>;
constructor(public loaderService: LoaderService, private http: HttpClient) {}
loadSomething() {
this.matches = this.http.get("https://jsonplaceholder.typicode.com/posts");
}
}
Example:
https://stackblitz.com/edit/angular-n6fzjm

Unable to get data when making httpClient.get in angular 5

I am trying to do a http.get using httpclient. However, and i am getting
ReferenceError: data is not defined
Inside my component class when subscribing to service method.
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { Observable } from 'rxjs/Observable';
const httpOptions = {
headers: new HttpHeaders()
.set('Authorization', 'Bearer xxxxx')
.set('Content-Type', 'application/json')
};
#Injectable()
export class SetsService {
constructor(private http: HttpClient) { }
getSet() {
return this.http.get('http://localhost:1234/api/users', httpOptions);
}
}
my component
import { Component, OnInit } from '#angular/core';
import { ActivatedRoute } from '#angular/router';
import { Router } from '#angular/router';
import { SetsService } from '../services/sets.service';
import { Observable } from 'rxjs/Observable';
#Component({
selector: 'app-sets',
templateUrl: './sets.component.html',
styleUrls: ['./sets.component.scss']
})
export class SetsComponent implements OnInit {
id: string = "";
set: any = {};
constructor(private route: ActivatedRoute, private router: Router, private _setsService: SetsService) {
this.route.params.subscribe(res => this.id = res.id);
}
ngOnInit() {
this.getSets();
}
getSets(){
this._setsService.getSet().subscribe(
(data) => { this.set = data },
err => console.error(err),
() => { console.log('done loading set') }
);
}}
When i look at the network the API call is successful and returning data.
Inside the html I am simply trying to print the set object.

The requested path contains undefined segment at index 0

authentication.service.ts in that my login service is define like this
import { Injectable } from '#angular/core';
import { Http, Headers, Response, RequestOptions } from '#angular/http';
import { Observable } from 'rxjs';
import 'rxjs/Rx';
import 'rxjs/add/operator/map'
import { AuthHttp } from 'angular2-jwt';
import { Router } from '#angular/router';
#Injectable()
export class AuthenticationService {
token: string;
redirectUrl: any;
constructor(public router: Router, private http: Http, private authHttp: AuthHttp) {
//set token if saved in local storage
if (localStorage.getItem('authToken') != null) {
try {
// var currentUser =
JSON.parse(localStorage.getItem('currentUser'));
this.token = localStorage.getItem('authToken');
// this.token = currentUser && currentUser.token;
} catch (e) {
localStorage.removeItem("authToken");
}
}
}
login(username: string, password: string) {
return this.http.post('http://localhost:3002/api/authenticate',({ username: username, password: password }))
.map(res => {
console.log(res);
var authToken = res.json().token;
localStorage.setItem('authToken', authToken);
let redirectUrlTemp: any;
redirectUrlTemp = this.redirectUrl;
this.redirectUrl = null;
if (!redirectUrlTemp) {
console.log(redirectUrlTemp);
redirectUrlTemp = ['/login'];
}
this.router.navigate(redirectUrlTemp);
},
err => {
//alert(error.text());
console.log(err.text());
});
}
logout(){
// clear token remove user from local storage to log user out
this.token = null;
localStorage.removeItem('authToken');
}
}
when i try to post data using postman it works properly but from angular 2 it not allowing to redirect from next page
Login.component.ts
import { Component, OnInit } from '#angular/core';
import { Router, ActivatedRoute } from '#angular/router';
import { AuthenticationService } from "app/services";
import { LoginRequest } from "app/models/models";
import { AlertService } from 'app/services';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
import { Http, Response } from '#angular/http';
#Component({
moduleId: module.id,
selector: 'login',
templateUrl: 'login.component.html'
})
export class LoginComponent implements OnInit {
model: any = {};
getLogin: LoginRequest[] = [];
loading = false;
error = '';
returnUrl: string;
constructor(
private route: ActivatedRoute,
private router: Router,
private http: Http,
private alertService: AlertService,
private authenticationService: AuthenticationService) { }
login() {
this.loading = true;
this.authenticationService.login(this.model.username, this.model.password).subscribe(data => {
this.router.navigate([this.returnUrl]);
},
error => {
this.alertService.error(error);
this.loading = false;
});
//let redirect = this.authenticationService.redirectUrl ? this.authenticationService.redirectUrl : '/allTask';
}
}
auth.guadr.ts
import { Injectable } from '#angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '#angular/router';
import { AuthenticationService } from "app/services";
#Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router, private authService: AuthenticationService) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if (localStorage.getItem('authToken')) {
// logged in so return true
return true;
}
this.authService.redirectUrl =[state.url];
this.router.navigate(['/login']);
return false;
}
}
This error means that navigate array parameter with index 0 is undefined.
In your case you didn't set this.returnUrl in Login.component.ts
this.router.navigate([this.returnUrl]);

Angular 2 – No data afte api call

I am playing around with angular 2 and the heroes tutorial. The Problem is that I always get an empty object no matter which api I call.
Here is the code:
app.compomnent.ts
import { Component, OnInit } from '#angular/core';
import { Http, Response } from '#angular/http';
// Add the RxJS Observable operators we need in this app.
import './rxjs-operators';
#Component({
selector: 'my-app',
template: `
<h1>Test</h1>
`
})
export class AppComponent implements OnInit {
constructor(private http: Http) {}
private error: any;
ngOnInit() {
var request = this.http.get('http://date.jsontest.com');
console.log("Request: " + request);
console.log("Map: " + request.map(res => res));
console.log("Complete: " + this.http.get('http://date.jsontest.com')
.map(res => res.json())
.catch(this.error));
}
}
main.ts:
// The usual bootstrapping imports
import { bootstrap } from '#angular/platform-browser-dynamic';
import { HTTP_PROVIDERS } from '#angular/http';
import { AppComponent } from './app.component';
bootstrap(AppComponent, [
HTTP_PROVIDERS
]);
The result in my console:
An Observable doesn't do anything until you subscribe to it because they are lazy
ngOnInit() {
this.http.get('http://date.jsontest.com')
.map(res => res.json())
.subscribe(
data => this.data = data,
() => console.log('done'),
err => this.error(err));
}