cant pass data from AppComponent to function - javascript

I send the email data to this.user in constructror.
So it storage in AppComponent, Next i need this variale in function getUserData for import some data...
but the console.log show undefined, and there is also error for users :
Cannot read property 'auth' of undefined
So what i made wrong? Why i cant pass data using this.?
Update
Now the user.String is string that contain a "xxxx#.xx.com"
But still i cant pass it there. this.user in getUserData is undefind :/
import { Component, OnInit } from '#angular/core';
import { RewardsComponent } from './rewards/rewards.component';
import { AngularFire,AuthProviders, AuthMethods, FirebaseAuthState } from 'angularfire2';
import { Router } from '#angular/router'
declare var firebase: any;
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'app works!';
userData: any = [];
user: String;
constructor(public af: AngularFire, private router: Router) {
af.auth.subscribe(auth => {
if(auth) {
this.user = auth.auth.email.toString();
}
})
}
ngOnInit() {
this.getUserData();
}
getUserData() {
var ref = firebase.database().ref("/user");
ref.orderByChild("email").equalTo(this.user).on("child_added", (snapshot) => {
this.userData.push(snapshot.val());
});
}
}

Probably
this.user = auth.auth.email;
is storing a string, something like 'someemail#gmail.com'
When you try to access
this.user.auth
there is no .auth attribute/key, because this.user is not an object.
Also, you have to keep in my mind that af.auth.subscribe is assynchronous code, therefore you can't access this.user in the ngOnInit method, because you don't know if the af.auth.subscribe has been called yet.

You should access email since you are assigning only email ,
console.log(this.user.email);
var users = this.user.email;
if you need to access the whole auth object, then assign it as,
this.user = auth;

Related

how do i assign data from the subscribe call to a local variable in Angular

I have tried to declare the variable inside the ngOnInit() but it goes out of scope. I would like to use the variable to iterate over the data and populate my html component. I have followed the answered questions on the same issue but most of them suggest calling a function inside the subscribe function, unfortunately in my case i just need to view the returned data.
import { Component, OnInit } from "#angular/core";
import { Playlist } from "../playlist";
import { PlaylistService } from "../playlist.service";
#Component({
selector: "app-market-place",
templateUrl: "./market-place.component.html",
styleUrls: ["./market-place.component.css"],
})
export class MarketPlaceComponent implements OnInit {
_playList: Playlist[] = []; //never gets assigned here
errorMessage;
constructor(private playListService: PlaylistService) {}
ngOnInit() {
this.playListService.getPlaylist().subscribe({
next: (playList) => {
this._playList = playList;
console.log(this._playList); // am able to log the data but its never assigned to my _playList variable
},
error: (err) => (this.errorMessage = err),
});
}
}
here is the service class
import { Injectable } from "#angular/core";
import {HttpClient, HttpErrorResponse} from '#angular/common/http'
import { Observable, throwError } from "rxjs";
import {catchError, map, tap} from 'rxjs/operators'
import { Playlist } from "./playlist";
#Injectable({
providedIn: "root",
})
export class PlaylistService {
private playListUrl = "https://reqres.in/api/users";
constructor(private http: HttpClient) {}
getPlaylist():Observable<Playlist[]> {
return this.http.get<Playlist[]>(this.playListUrl).pipe(
map((response) => <Playlist[]>response),
catchError(this.handleError),
);
}
private handleError(err:HttpErrorResponse){
let errorMessage = '';
if (err.error instanceof ErrorEvent){
errorMessage = `An error occurred: ${err.error.message}`
}else {
errorMessage = `Server returned code: ${err.status}, error message is: ${err.message}`;
}
console.error(errorMessage);
return throwError(errorMessage)
}
}
I do not know, what your Playlist object looks like, but maybe I have a simple idea, that could solve your issue. I suppose that console.log can not show the array of your objects. Did you try the following?
console.log(this._playList[0]);

Ionic How to Pass variable to firebase equalTo method

I have already managed to fetch data form firebase.problem is when i'm going to filter data according to the id it doesn't work.
import { Component, OnInit } from '#angular/core';
import { ActivatedRoute } from '#angular/router';
import { AngularFireDatabase, AngularFireList ,} from 'angularfire2/database';
import { Observable } from 'rxjs'
import { query } from '#angular/core/src/render3';
import { Key } from 'protractor';
class postview {
constructor(public title) { }
}
#Component({
selector: 'app-news-view',
templateUrl: './news-view.page.html',
styleUrls: ['./news-view.page.scss'],
})
export class NewsViewPage implements OnInit {
id: string;
public books: AngularFireList<postview[]>;
itemlol: Observable<any>;
posts: Observable<any[]>;
constructor(private route: ActivatedRoute , db: AngularFireDatabase) {
let idp :string = this.id;
this.posts = db.list('Posts' ,ref => {
return ref.orderByChild('Post_Id').equalTo(idp)
}).valueChanges();
// this.itemlol= db.object('Posts').valueChanges();
}
ngOnInit() {
this.id = this.route.snapshot.paramMap.get('id');
console.log(this.id);
console.log(this.posts);
}
}
in the section return ref.orderByChild('Post_Id').equalTo(idp) I need to pass variable in equalTo(). It should change according to the user instructions
Example
equalTo(01)
equalTo(02)
This is my firebase database:
The constructor is called before ngOnInit so the value for this.id will be undefined at the time of the query.
You should get the Parameters in the constructor
this.id = this.route.snapshot.paramMap.get('id');
let idp :string = this.id;
this.posts = db.list('Posts' ,ref => ref.orderByChild('Post_Id').equalTo(idp) ).valueChanges();

Cannot access variable outside the subscription

I have an component in angular. I get data from the API and I instantiate a new object to create a map. But I can't access a variable outside the subscribe function. I also can't access my method.
maps.service.ts
This part, get data form api
import { Injectable } from '#angular/core';
import {HttpClient} from '#angular/common/http';
#Injectable()
export class MapsService {
constructor(private http: HttpClient) { }
getMap(params) {
console.log('Service', params);
return this.http.get('/api/posts/' + params.id);
}
}
map.component.ts
Here, where I build the map with google in the future
import { Component, OnInit } from '#angular/core';
import {MapsService} from '../maps.service';
import {ActivatedRoute} from '#angular/router';
import {MapPath} from '../map-path';
#Component({
selector: 'app-maps',
templateUrl: './maps.component.html',
styleUrls: ['./maps.component.css']
})
export class MapsComponent implements OnInit {
results: any;
params: {};
test: any;
constructor(
private mapsService: MapsService,
private route: ActivatedRoute,
) { }
ngOnInit() {
this.route.params.subscribe( params => {
this.params = params;
});
this.mapsService.getMap(this.params).subscribe(
data => {
this.results = data;
this.test = new MapPath(data, 'test');
},
err => {
console.log('Error occured', err);
});
console.log('this.test', this.test.getX());
console.log('this.results', this.results);
}
}
map-path.ts
Here get the different properties from geoJSON
export class MapPath {
test: string;
constructor(path: any, test: string) {
this.test = test;
console.log('Path', path);
console.log('test', test);
}
getX() {
return this.test;
}
}
Thanks.
Your problem is that Observables are async functions, meaning your subscription callback will happen later than the console.log calls following your this.mapsService.getMap call.
This is guaranteed by async nature of Observables.
You can either move your console logs inside of the subscribe function or create another subscription.
Hope this helps.

Fetch the data from GITHUB API

I want to get all the data from github API. But it doesn't work for me.
My .ts file is below:
import { Component } from '#angular/core';
import { GitTakeService } from "app/git-take.service";
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
user:any;
constructor(private gittakeService:GitTakeService ){
this.gittakeService.getUser().subscribe(user=>{
debugger;
this.user=user;
console.log(user);
})
}
}
My service is below:
import { Injectable } from '#angular/core';
import {Http,Response, Headers} from '#angular/http'
import'rxjs/add/operator/map';
#Injectable()
export class GitTakeService {
constructor(private http:Http) { }
getUser(){
debugger;
return this.http.get("http://api.github.com/users")
.map(
(resp:Response)=>{
return resp.json().response;
}
);
}
}
When consoling the user in .ts file, it shows undefined. My view file is like this:
{{user}}
Anyone please help me to solve this problem?
What you are receiving is an array, so you want to use resp.json() instead of resp.json().response there is no such property like response in your response. So your map should look like this:
getUser(){
debugger;
return this.http.get("http://api.github.com/users")
.map((resp:Response)=>{
return resp.json();
});
}
and in your component I would name the array users instead of user, since there are several users in your response. Also I suggest you keep anything unnecessary from the constructor and use OnInit instead:
users = [];
constructor(private gittakeService:GitTakeService ){ }
ngOnInit() {
this.gittakeService.getUser()
.subscribe(data => {
this.users = data;
});
}
Then you can iterate the array and use the property names to show the properties of one user object:
<div *ngFor="let user of users">
{{user.login}}
</div>
resp.json().response is undefined resp.json() is what you want
the service function:
getUser(){
return this.http.get("http://api.github.com/users")
.map(
(resp:Response)=>{
return resp.json();
}
);
}`
and the component:
this.gittakeService.getUser().subscribe(users=>{
this.user=users[0];
console.log(user);
})

angular2 saving response from firebase to a model

Thanks a lot for reading this question. Have been struggling for a while, will be great if someone point out what I'm doing wrong here.
I'm getting result from firebase and trying to save it in the User Model, but I'm getting this error
Uncaught TypeError: Cannot set property 'users' of null.
import { Component, OnInit, EventEmitter, Output } from '#angular/core';
import { User } from '../user.ts';
import { UserComponent } from './user.component';
declare var firebase: any;
#Component({
moduleId: module.id,
selector: 'trafford-user-list',
templateUrl: 'user-list.component.html',
styleUrls: ['user-list.component.css'],
directives: [ UserComponent ]
})
export class UserListComponent implements OnInit {
private users: User[] = [{ name: 'sosk', email: 'dfdok', password: 'asdf'}];
private user: User;
#Output() selected = new EventEmitter<User>();
constructor() { }
ngOnInit() {
this.getUsers();
}
getUsers() {
firebase.database().ref('accounts').on('value', function(snapshot) {
this.users = snapshot.val();
});
}
onSelected(user: User) {
this.selected.emit(user);
}
}
When I try to write the response in the console its working. But this.users don't have any scope inside that firebase callback. I'm very new to angular any help would be appreciated.
Use arrow function (=>) to preserve scope
getUsers() {
firebase.database().ref('accounts').on('value', (snapshot) => {
this.users = snapshot.val();
});
}

Categories

Resources