angular resolver does not have access to angular service properties - javascript

i have an anagular service called authservice ,which looks like this:
import { Injectable } from '#angular/core';
import { Http, Headers, RequestOptions, Response } from '#angular/http';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
import { JwtHelperService} from '#auth0/angular-jwt';
#Injectable()
export class AuthService {
public DecdedToken: any;
userToken: any;
public userid: any;
helper: any = new JwtHelperService();
baseUrl = 'http://localhost:5000/api/auth/';
// userToken: any;
constructor(private http: Http , private jwthelpservicee: JwtHelperService) {}
login(model: any) {
return this.http.post(this.baseUrl + 'login', model, this.requestOptions()).map((response: Response) => {
const user = response.json();
if (user && user.stringToken) {
this.userToken = user.stringToken;
localStorage.setItem('token', user.stringToken);
this.DecdedToken = this.helper.decodeToken(user.stringToken);
this.userid = this.DecdedToken.nameid;
// console.log(this.userid);
// onsole.log('so far so good');
}
}).catch(this.HandleError);
}
register(model: any) {
return this.http.post(this.baseUrl + 'register', model, this.requestOptions()).catch(this.HandleError);
}
private requestOptions() {
const headers = new Headers({ 'Content-type': 'application/json' });
return new RequestOptions({ headers: headers });
}
IsLoggedIn() {
return !this.jwthelpservicee.isTokenExpired();
}
private HandleError(error: any) {
const applicationerror = error.headers.get('Application-Error');
if (applicationerror) {
return Observable.throw(applicationerror);
}
const serverError = error.json();
let modelStateErrors = '';
if (serverError) {
for (const key in serverError) {
if (serverError[key]) {
modelStateErrors += serverError[key] + '\n';
}
}
}
return Observable.throw(modelStateErrors || 'server error');
}
}
in login method DecodedToken gets its value.
i have a resolver too, in which i am trying to get a value of a property from authsercvice
import { Resolve, Router, ActivatedRouteSnapshot } from '../../../node_modules/#angular/router';
import { User } from '../_Models/user';
import { Injectable } from '../../../node_modules/#angular/core';
import { UserService } from '../_services/User.service';
import { AlertifyService } from '../_services/alertify.service';
import { Observable } from '../../../node_modules/rxjs';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/catch';
import { AuthService } from '../_services/auth.service';
#Injectable()
export class MemberEditResolver implements Resolve<User> {
constructor(private userservice: UserService ,
private router: Router ,
private alertify: AlertifyService,
private authservice: AuthService) {
}
resolve(route: ActivatedRouteSnapshot): Observable<User> {
console.log(this.authservice.userid);
return this.userservice.getuser(this.authservice.DecdedToken.nameid).catch(error => {
this.alertify.error('error');
this.router.navigate(['/members']);
return Observable.of(null);
});
}
}
as you can see i have defined DecdedToken as a public property, inside the authservice this property has value, but when i want to access it from resolver ,i get null or undefined...

Related

ERROR TypeError: Cannot read property 'subscribe' of undefined on POST HTTP Call - Angular [8]

I'm trying to Post data to rest API. I'm using Postman for my rest API.
Getting Cannot read property 'subscribe' of undefined on POST HTTP Call in console log:
My rest API: "dradiobeats.x10host.com/api/areas"
userService.ts:
import { Injectable, Input } from "#angular/core";
import { HttpClient, HttpHeaders } from "#angular/common/http";
import { userArray } from "./users.model";
import { Observable } from "rxjs";
const httpOptions = {
headers: new HttpHeaders({
"Content-Type": "application/json",
Authorization:
"Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImYyOTc3OTBmODc3ODlhYzg3MGE2ZmU3YTY0YzY2YmIwOGU4M2Q0ZmQzY2IyNmNiNWU3NDEzMTFmZjExMDk4NTA5NWUzN2IxN2I5YmI2YmFjIn0.eyJhdWQiOiIyIiwianRpIjoiZjI5Nzc5MGY4Nzc4OWFjODcwYTZmZTdhNjRjNjZiYjA4ZTgzZDRmZDNjYjI2Y2I1ZTc0MTMxMWZmMTEwOTg1MDk1ZTM3YjE3YjliYjZiYWMiLCJpYXQiOjE1NzU4NzM4MzksIm5iZiI6MTU3NTg3MzgzOSwiZXhwIjoxNjA3NDk2MjM5LCJzdWIiOiIyIiwic2NvcGVzIjpbXX0.J3nMXcPpqlRVvIRkrVAMblSUwdlXFmrkn9SPD2WE1DwdiqAMdhay8zAeD550ta9qWiNxHOKMAWF8t3H9cIgItaB9ZX2CxoxzS5P1nJFzit8qxiB-gzJL3mpybrnLtrKGjxsM5i_lBvdJsnhWzi15jKWIu-RNxUYPnXCjuxnXYEiyoJg17hsYUh4910VfFWx4R3WvH7WOvczF53IDKyX5fSTt4WSJUqciuNepkO6Klc8sj_yPmDPQltUjUXSSplkOQ8sL5uHk7PmzSjIfoR8RC0A-YQqI9mbZMTyJ0IyKoAHvRHF8q1cW5qfUmLXTgxcCTmFPqXqIlcAoOoJMCxke5fl0PuK0rgU7dxouATk_3B6cio7-7Zgps0iopDpk2nm-o40mjSiOUGb2kyKckYN09orYuan5wEd1KJ873ejKEgBWOhJu4gQFps8M9VoDXncAqMxeBqbUY1UZENx_n6uduQ_SAY4rgIUFCixfNc5Y_-HLDa108u4-z3APGbdxrhEdZXyHz9xQTaLrWcU_iCJ5g_ObT5VGZHtawZbfOYm2ZZpjPiCZpXunhrsbAcHBX64akWcehmT2gUJqPsxvaObKN3nayML1NHtdZGgAHUE89clhIH610Fod0C_jMTqpU7IkY9aSU781HsQVlHNw3qGbTinWfYPDBG0Lkp9NnmRe9BU",
Accept: "application/json"
})
};
#Injectable({
providedIn: "root"
})
export class UsersService {
users$: userArray[];
apiUrl = "http://dradiobeats.x10host.com/api/areas";
delUrl = "http://dradiobeats.x10host.com/api/areas";
constructor(private _http: HttpClient) {}
getUsers() {
return this._http.get<userArray[]>(this.apiUrl);
}
deleteUser(id: userArray): Observable<userArray> {
const url = `${this.apiUrl}/${id}`;
console.log();
return this._http.delete<userArray>(url, httpOptions);
}
onSubmit(users$: userArray): Observable<userArray> {
console.log(users$);
this._http.post<userArray>(this.apiUrl, users$, httpOptions);
}
}
add-post.component.ts:
import { Component, OnInit } from "#angular/core";
import { UsersService } from "src/app/users.service";
import { userArray } from "src/app/users.model";
#Component({
selector: "app-add-posts",
templateUrl: "./add-posts.component.html",
styleUrls: ["./add-posts.component.css"]
})
export class AddPostsComponent implements OnInit {
name: string;
description: string;
domain: string;
picture: string;
id: number = 29;
constructor(private userService: UsersService) {}
users: userArray[];
ngOnInit() {}
onSubmit() {
const users$ = {
name: this.name,
description: this.description,
domain: this.domain,
picture: this.picture
};
this.userService.onSubmit(users$).subscribe();
}
}
Can someone please help?
You need to return the http call observable
Try:
onSubmit(users$: userArray): Observable<userArray> {
console.log(users$);
return this._http.post<userArray>(this.apiUrl, users$, httpOptions);
}
As onSubmit() has an Observable signature, it must return an observable. You must change your function to 'return this.http.post ...'
You forgot to return, As only observable can be subscribe
import { Injectable, Input } from "#angular/core";
import { HttpClient, HttpHeaders } from "#angular/common/http";
import { userArray } from "./users.model";
import { Observable } from "rxjs";
const httpOptions = {
headers: new HttpHeaders({
"Content-Type": "application/json",
Authorization:
"Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImYyOTc3OTBmODc3ODlhYzg3MGE2ZmU3YTY0YzY2YmIwOGU4M2Q0ZmQzY2IyNmNiNWU3NDEzMTFmZjExMDk4NTA5NWUzN2IxN2I5YmI2YmFjIn0.eyJhdWQiOiIyIiwianRpIjoiZjI5Nzc5MGY4Nzc4OWFjODcwYTZmZTdhNjRjNjZiYjA4ZTgzZDRmZDNjYjI2Y2I1ZTc0MTMxMWZmMTEwOTg1MDk1ZTM3YjE3YjliYjZiYWMiLCJpYXQiOjE1NzU4NzM4MzksIm5iZiI6MTU3NTg3MzgzOSwiZXhwIjoxNjA3NDk2MjM5LCJzdWIiOiIyIiwic2NvcGVzIjpbXX0.J3nMXcPpqlRVvIRkrVAMblSUwdlXFmrkn9SPD2WE1DwdiqAMdhay8zAeD550ta9qWiNxHOKMAWF8t3H9cIgItaB9ZX2CxoxzS5P1nJFzit8qxiB-gzJL3mpybrnLtrKGjxsM5i_lBvdJsnhWzi15jKWIu-RNxUYPnXCjuxnXYEiyoJg17hsYUh4910VfFWx4R3WvH7WOvczF53IDKyX5fSTt4WSJUqciuNepkO6Klc8sj_yPmDPQltUjUXSSplkOQ8sL5uHk7PmzSjIfoR8RC0A-YQqI9mbZMTyJ0IyKoAHvRHF8q1cW5qfUmLXTgxcCTmFPqXqIlcAoOoJMCxke5fl0PuK0rgU7dxouATk_3B6cio7-7Zgps0iopDpk2nm-o40mjSiOUGb2kyKckYN09orYuan5wEd1KJ873ejKEgBWOhJu4gQFps8M9VoDXncAqMxeBqbUY1UZENx_n6uduQ_SAY4rgIUFCixfNc5Y_-HLDa108u4-z3APGbdxrhEdZXyHz9xQTaLrWcU_iCJ5g_ObT5VGZHtawZbfOYm2ZZpjPiCZpXunhrsbAcHBX64akWcehmT2gUJqPsxvaObKN3nayML1NHtdZGgAHUE89clhIH610Fod0C_jMTqpU7IkY9aSU781HsQVlHNw3qGbTinWfYPDBG0Lkp9NnmRe9BU",
Accept: "application/json"
})
};
#Injectable({
providedIn: "root"
})
export class UsersService {
users$: userArray[];
apiUrl = "http://dradiobeats.x10host.com/api/areas";
delUrl = "http://dradiobeats.x10host.com/api/areas";
constructor(private _http: HttpClient) {}
getUsers() {
return this._http.get<userArray[]>(this.apiUrl);
}
deleteUser(id: userArray): Observable<userArray> {
const url = `${this.apiUrl}/${id}`;
console.log();
return this._http.delete<userArray>(url, httpOptions);
}
onSubmit(users$: userArray): Observable<userArray> {
console.log(users$);
return this._http.post<userArray>(this.apiUrl, users$, httpOptions);
}
}

Angular 6 : Issue of component data binding

I call service which make http call, I assign response to component variable now when I try access that component variable to view it display blank.
Means component variable assign in subscribe successfully but cant acceess in html view.
I think view is loaded before values assign to component data.
component
import {Component, OnInit, ChangeDetectionStrategy} from '#angular/core';
import { UserService } from '../../../../../core/services/users/user.service';
import { HttpClient } from '#angular/common/http';
#Component({
selector: 'm-user-list',
templateUrl: './user-list.component.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class UserListComponent implements OnInit {
list;
roles = {};
current_page: any
totalRecords: any
public showContent: boolean = false;
constructor(private userService: UserService, private http: HttpClient) {
}
ngOnInit() {
this.getRecords();
}
getRecords(){
this.getResultedPage(1);
}
getResultedPage(page){
return this.userService.getrecords()
.subscribe(response => {
this.list = response.data;
});
}
}
Service
import { Injectable } from '#angular/core';
import { Observable, of, throwError } from 'rxjs';
import { HttpClient, HttpParams , HttpErrorResponse, HttpHeaders } from '#angular/common/http';
import { map, catchError, tap, switchMap } from 'rxjs/operators';
const httpOptions = {
headers: new HttpHeaders({'Content-Type': 'application/json'})
};
import { UtilsService } from '../../services/utils.service';
import { AppConfig } from '../../../config/app'
#Injectable({
providedIn: 'root'
})
export class UserService{
public appConfig: AppConfig;
public API_URL;
constructor(private http: HttpClient, private util: UtilsService) {
this.appConfig = new AppConfig();
this.API_URL = this.appConfig.config.api_url;
}
private extractData(res: Response) {
let body = res;
return body || { };
}
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
// return an observable with a user-facing error message
return throwError('Something bad happened; please try again later.');
};
getrecords(): Observable<any> {
return this.http.get('/api/users', httpOptions).pipe(
map(this.extractData),
catchError(this.handleError));
}
}

save and fetch on firebase in angular is not working

Why my movie component is not updating after fetching the data. Also not saving the data if I have added a new movie or made changes in existing movies.
It is just saving and fetching the data which is written in movie.service.ts file. Also the fetched data is not rendering on the movie component.
Data-storage.service
import { Injectable } from '#angular/core';
import { MovieService } from '../movies/movies.service';
import { HttpClient, HttpHeaders, HttpParams, HttpRequest } from '#angular/common/http';
import { Movie } from '../movies/movie.model';
import { Observable} from 'rxjs';
import { map } from 'rxjs/operators';
// import 'rxjs/Rx';
// import 'rxjs/Rx';
#Injectable({
providedIn: 'root'
})
export class DataStorageService {
constructor(private httpClient: HttpClient,
private movieService: MovieService,) { }
storeMovies(): Observable<any> {
const req = new HttpRequest('PUT', 'https://moviepedia-4211a.firebaseio.com/movies.json', this.movieService.getMovies(), {reportProgress: true});
return this.httpClient.request(req);
}
getMovies() {
this.httpClient.get<Movie[]>('https://moviepedia-4211a.firebaseio.com/movies.json', {
observe: 'body',
responseType: 'json'
})
.pipe(map(
(movies) => {
console.log(movies);
return movies;
}
))
.subscribe(
(movies: Movie[]) => {
this.movieService.setMovies(movies);
}
);
}
}
movie.service.ts :
import { Injectable } from '#angular/core';
import {Subject} from 'rxjs';
import { Movie } from './movie.model';
#Injectable()
export class MovieService {
moviesChanged = new Subject<Movie[]>();
private movies: Movie[] = [
new Movie(
'Movie test', 'Movie details', 'https://s18672.pcdn.co/wp-content/uploads/2018/01/Movie-300x200.jpg'
),
new Movie(
'Movie test 2', 'Movie details 2', 'https://s18672.pcdn.co/wp-content/uploads/2018/01/Movie-300x200.jpg'
),
new Movie(
'Movie test 2', 'Movie details 3', 'https://s18672.pcdn.co/wp-content/uploads/2018/01/Movie-300x200.jpg'
)
];
constructor(){}
getMovie(index: number) {
return this.movies[index];
}
getMovies() {
return this.movies.slice();
}
addMovie(movie: Movie) {
this.movies.push(movie);
this.moviesChanged.next(this.movies.slice());
}
updateMovie(index: number, newMovie: Movie) {
this.movies[index] = newMovie;
this.moviesChanged.next(this.movies.slice());
}
deleteMovie(index: number) {
this.movies.splice(index, 1);
this.moviesChanged.next(this.movies.slice());
}
setMovies(movies: Movie[]) {
this.movies = movies;
this.moviesChanged.next(this.movies.slice());
}
}
movie.model.ts
export class Movie {
public name: string;
public description: string;
public imagePath: string;
constructor(name: string, description: string, imagePath: string) {
this.name = name;
this.description = description;
this.imagePath = imagePath;
}
}
movie.component :
import { Component, OnInit, EventEmitter, Output, OnDestroy } from '#angular/core';
import { Movie } from '../movie.model'
import { MovieService } from '../movies.service';
import { Router, ActivatedRoute } from '#angular/router';
import { Subscription } from 'rxjs';
#Component({
selector: 'app-movie-list',
templateUrl: './movie-list.component.html',
styleUrls: ['./movie-list.component.css']
})
export class MovieListComponent implements OnInit, OnDestroy {
subscription: Subscription;
movies: Movie[] = [];
constructor(private movieService: MovieService,
private router: Router,
private route: ActivatedRoute) { }
ngOnInit() {
this.subscription = this.movieService.moviesChanged
.subscribe(
(movies: Movie[]) => {
this.movies = movies;
}
);
this.movies = this.movieService.getMovies();
}
onNewMovie() {
this.router.navigate(['new'], {relativeTo: this.route});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
What can I do save and fetch data which will render on page.
I think the problem with your PUT request is that the url you used expects json but you are sending Movie object. you should send and receive json to this url.
wish it helps ...

How to access private method in spec file (Karma - Angular) [duplicate]

I have been going round in circles trying to unit test a Service (AuthService) that depends upon AngularFireAuth.
I am trying to find a way to mock, or highjack the Observable AngularFireAuth.authState instead of the Service actually talking to Firebase.
Here is my test spec:
import { inject, TestBed } from '#angular/core/testing';
import { AngularFireModule } from 'angularfire2';
import { AngularFireAuth, AngularFireAuthModule } from 'angularfire2/auth';
import * as firebase from 'firebase/app';
import 'rxjs/add/observable/of';
// import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Rx';
import { AuthService } from './auth.service';
import { environment } from '../../environments/environment';
const authState: firebase.User = null;
const mockAngularFireAuth: any = { authState: Observable.of(authState) };
describe('AuthService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [AngularFireModule.initializeApp(environment.firebaseAppConfig)],
providers: [
{ provider: AngularFireAuth, useValue: mockAngularFireAuth },
AuthService
]
});
});
it('should be defined', inject([ AuthService ], (service: AuthService) => {
expect(service).toBeDefined();
}));
it('.authState should be null', inject([ AuthService ], (service: AuthService) => {
expect(service.authState).toBe(null);
}));
});
And here is my (simplified) Service:
import { Injectable } from '#angular/core';
import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app';
import { Observable } from 'rxjs/Rx';
#Injectable()
export class AuthService {
private authState: firebase.User;
constructor(private afAuth: AngularFireAuth) { this.init(); }
private init(): void {
this.afAuth.authState.subscribe((authState) => {
if (authState === null) {
this.afAuth.auth.signInAnonymously()
.then((authState) => {
this.authState = authState;
})
.catch((error) => {
throw new Error(error.message);
});
} else {
this.authState = authState;
}
}, (error) => {
throw new Error(error.message);
});
}
public get currentUser(): firebase.User {
return this.authState ? this.authState : undefined;
}
public get currentUserObservable(): Observable<firebase.User> {
return this.afAuth.authState;
}
public get currentUid(): string {
return this.authState ? this.authState.uid : undefined;
}
public get isAnonymous(): boolean {
return this.authState ? this.authState.isAnonymous : false;
}
public get isAuthenticated(): boolean {
return !!this.authState;
}
public logout(): void {
this.afAuth.auth.signOut();
}
}
I get the error Property 'authState' is private and only accessible within class 'AuthService'.
Of course it is, but I don't want to actually access it — I want to mock or highjack it so I can control it's value from within my test spec. I believe I am way off-course with my code here.
Please note I am using version ^4 of AngularFire2 and there were breaking changes introduced; documented here: https://github.com/angular/angularfire2/blob/master/docs/version-4-upgrade.md
Encapsulated members can be reflected.
The hard way:
expect(Reflect.get(service, 'authState')).toBe(null);
The easy way:
expect(service['authState']).toBe(null);
expect((service as any).authState).toBe(null);

Angular 5 component expecting an argument

Im trying a simple profile app, and all the sudden Im getting error TS2554
ERROR in /app/components/profile/profile.component.ts(25,3): error TS2554: Expected 1 arguments, but got 0.
import { Component, OnInit } from '#angular/core';
import { AuthService } from '../../services/auth.service';
import { FlashMessagesService } from 'angular2-flash-messages';
import { Router } from '#angular/router';
#Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
user: Object;
constructor(
private auth: AuthService,
private flashMsg: FlashMessagesService,
private router: Router
) {
}
ngOnInit() {
this.auth.getProfile().subscribe( profile => {
this.user = profile.user;
},
err => {
return false;
});
}
}
auth.service.ts
import { Injectable } from '#angular/core';
import { Http, Headers } from '#angular/http';
import 'rxjs/add/operator/map';
import { tokenNotExpired } from 'angular2-jwt';
#Injectable()
export class AuthService {
authToken: any;
user: any;
constructor(
private http: Http
) {
}
getProfile(user) {
let headers = new Headers();
this.loadToken();
headers.append('Authorization', this.authToken);
headers.append('Content-Type','application/json');
return this.http.get('http://localhost:3000/users/profile', {headers:headers})
.map(res => res.json());
}
loadToken() {
const token = localStorage.getItem('id_token');
this.authToken = token;
}
}
Your getProfile is expecting an argument named user but you are not passing it from the component
You need to pass an argument as follows,
this.auth.getProfile(user).subscribe( profile => {
this.user = profile.user;
},
err => {
return false;
});
or if you don't need an argument , remove it from your service method.

Categories

Resources