Angular: How can i push an observable to a list - javascript

I get an Error message that i cant push an undefined variable to my list.
This is my code in the component.ts
for (const file of this.allFiles) {
this.uploadFileService
.validate(file)
.subscribe( valid => {
this.validList.push(valid);
})
}
This is my Service:
validate(file: File): Observable<boolean> {
const data: FormData = new FormData();
data.append('file', file);
return this.http.post<boolean>(`${this.url}/validate`,data);
}
How can I push to the list?

You will get this error if you do not initialize the array ([]) first before pushing. Please declare the variable validList: Array<any> = [] at the top of the component before pushing data inside.
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit{
name = 'Angular';
validList: Array<any> = [];
ngOnInit() {
this.validList.push(true);
}
}
Issue replicated stackblitz
Working stackblitz

Related

displaying items from DB using Angular 12

the Item file
component file
the data service file
when I test my code with console log statements it says data from service is undefined
import { Component, OnInit } from '#angular/core';
import { Item } from '../item';
import { DataService } from '../data.service';
#Component({
selector: 'app-shopping-item',
templateUrl: './shopping-item.component.html',
styleUrls: ['./shopping-item.component.css'],
providers: [DataService]
})
export class ShoppingItemComponent implements OnInit {
shoppingItemList: Item[] = [];
constructor(private dataservice: DataService){}
getItems(){
this.dataservice.getShoppingItems()
.subscribe(items =>{
this.shoppingItemList.push(items),
console.log('data from dataservice '+ this.shoppingItemList[0].itemName);
})
}
addItem(form: any){
console.log(form)
}
ngOnInit(): void {
this.getItems();
}
}
If you are receiving an array from the API call, then you need to either assign it directly to the property (1) or destructure the array into the property (2)
Currently I guess you are pushing an array inside an array, which might lead to undefined error!
import { Component, OnInit } from '#angular/core';
import { Item } from '../item';
import { DataService } from '../data.service';
#Component({
selector: 'app-shopping-item',
templateUrl: './shopping-item.component.html',
styleUrls: ['./shopping-item.component.css'],
providers: [DataService]
})
export class ShoppingItemComponent implements OnInit {
shoppingItemList: Item[] = [];
constructor(private dataservice: DataService){}
getItems(){
this.dataservice.getShoppingItems()
.subscribe(items =>{
this.shoppingItemList = items; // solution 1
// this.shoppingItemList.push(...items); // solution 2
console.log('data from dataservice '+ this.shoppingItemList[0].itemName);
})
}
addItem(form: any){
console.log(form)
}
ngOnInit(): void {
this.getItems();
}
}

How to render a list retrieved from firebase

I want to render a list in angular project with data retrieved from firebase, but I cannot render it to my list.
I tried on Angular 7
//this is my ts code
import { Component } from '#angular/core';
import { AngularFireDatabase } from '#angular/fire/database';
import { PassThrough } from 'stream';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
courses: any[];
constructor(db: AngularFireDatabase) {
db.list('/courses').snapshotChanges().subscribe(courses =>{
this.courses = courses;
console.log(this.courses);
});
}
}
//this is the html
<ul>
<li *ngFor="let course of courses">
{{course.value}}
</li>
</ul>
I want it to show like this
course1
course2
but the list are rendered with only a dot like this
-
inside subscribe() this does not reference to courses you need to assign this to another variable like let self=this;
Try the following code i hope this will work for you
import { Component } from '#angular/core';
import { AngularFireDatabase } from '#angular/fire/database';
import { PassThrough } from 'stream';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
courses: any[];
constructor(db: AngularFireDatabase) {
let self=this;
db.list('/courses').snapshotChanges().subscribe(courses =>{
self.courses = courses;
console.log(courses);
});
}
}
Small issue, you cannot assign the node to this.courses
export class AppComponent {
courses: any[];
constructor(db: AngularFireDatabase) {
db.list('/courses').snapshotChanges().pipe(
map(changes =>
changes.map(c => ({ key: c.payload.key, ...c.payload.val() }))
)
).subscribe(courses =>{
this.courses = courses;
console.log(this.courses);
});
}
}
ref: https://github.com/angular/angularfire2/blob/master/docs/rtdb/lists.md
Also, make sure that course.value, "value" property exists in course object.
<ul>
<li *ngFor="let course of courses">
{{course.value}} <-- here ??
</li>
</ul>

How to push object into an object array in Angular 6?

I have an empty object array like this groupList:any = {} and now I want to push an object into it. I am trying to name and description as an object.
It is not an array, array is represented like [] , probably you need
groupList:any = [];
and then,
this.groupList.push({name:'you',description:'what is array'});
app.component.ts
declare var require: any;
import { Component } from '#angular/core';
import { OnInit } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent{
groupList:any = [];
arrayVal:any;
currentVal : any;
title = 'projectchart';
public array = [{"id":1},{"id":3},{"id":5}];
getPrev(){
this.array.forEach((item, index) => {
this.groupList.push(item.id);
});
console.log(this.groupList);
}
}
app.component.html
<button (click) ="getVal()">Previous Value</button>

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);
})

cant pass data from AppComponent to function

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;

Categories

Resources