Method some() doesn't work as expected in Angular 8 - javascript

I have an Angular app and I want to add follow/unfollow functionality for users. I'm trying to add isFollowed flag, so I will be able to know if user is followed or no, and depending on that I will show 2 different buttons: Follow and Unfollow. I'm using some() method for this purposes but it doesn't work. It shows me that isFollowed flag is undefined although it should show true or false. I don't understand where the problem is, here is my HTML relevant part:
<button *ngIf="!isFollowing; else unfollowBtn" class="btn" id="btn-follow" (click)="follow(id)">Follow </button>
<ng-template #unfollowBtn><button class="btn" id="btn-follow" (click)="unFollow(id)">Unfollow</button></ng-template>
TS component relevant part:
import { Component, OnInit } from '#angular/core';
import { Router, ActivatedRoute } from "#angular/router";
import { AuthenticationService } from '#services/auth.service';
import { FollowersService } from '#services/followers.service';
#Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
user;
id;
followers;
isFollowing: boolean;
constructor(
private authenticationService: AuthenticationService,
private followersService: FollowersService,
private router: Router,
private route: ActivatedRoute,
) { }
ngOnInit() {
this.id = this.route.snapshot.paramMap.get("id");
this.authenticationService.getSpecUser(this.id).subscribe(
(info => {
this.user = info;
})
);
this.followersService.getFollowing().subscribe(
data => {
this.followers = data;
this.isFollowing = this.followers.some(d => d.id == this.user.id);
}
);
}
follow(id) {
console.log('follow btn');
this.followersService.follow(id).subscribe(
(data => console.log(data))
)
this.isFollowing = true;
}
unFollow(id) {
console.log('unFollow btn');
this.followersService.unFollow(id).subscribe(
(data => console.log(data))
)
this.isFollowing = false;
}
}
Any help would be appreciated.

If you want it called everytime and to make sure this.user is populated. Then you could use a forkJoin
forkJoin(
this.authenticationService.getSpecUser(this.id),
this.followersService.getFollowing()
).pipe(
map(([info, data]) => {
// forkJoin returns an array of values, here we map those values to the objects
this.user = info;
this.followers = data;
this.isFollowing = this.followers.some(d => d.id == this.user.id);
})
);
Not tested this because I didn't have time. If you make a StackBlitz we could see it in action and try from there.
Hope this helps.

Related

Angular: How to kinda refresh the ngOnInit method

I have a sidebar with different redirects of specific products categories, when these buttons are clicked it redirects to a component that gets the URL params and makes a consult to service and retrieves the data of that specific category, the thing is, when a click it the first time, it works, but the second time it does not, it only changes the URL but does not refresh the data
sidebar.component.html
<div class="list-group">
<a [routerLink]="['products/category']" [queryParams]="{name:category.name}" class="list-group-item"
*ngFor="let category of categories">{{category.name}}</a>
</div>
And the component that makes the magic
export class ViewAllProductsByCategoryComponent implements OnInit {
searchCategory: any;
products: Product;
constructor(private activatedRoute: ActivatedRoute, private productsService: ProductsService) {
}
ngOnInit(): void {
this.activatedRoute.queryParams.subscribe(res => {
this.searchCategory = res.name;
});
this.productsService.searchCategoryProducts(this.searchCategory).subscribe(res => {
this.products = res;
console.log(this.products);
});
}
}
So, how do I refresh the data?
Angular by default doesn't re-initialize an already loaded component.
But there is a way to bypass that feature:
let newLocation = `/pathName/5110`;
// override default re use strategy
this.router
.routeReuseStrategy
.shouldReuseRoute = function () {
return false;
};
this.router
.navigateByUrl(newLocation)
.then(
(worked) => {
// Works only because we hooked
// routeReuseStrategy.shouldReuseRoute
// and explicitly told it don't reuse
// route which forces a reload.
// Otherwise; the url will change but new
// data will not display!
},
(error) => {
debugger;
}
);
Just set the .shouldReuseRoute function to return false, that way the component will reload.
Here's more detail on that topic.
https://dev.to/jwp/angular-s-naviation-challenges-20i2
You can also configure the router to reuse the route.
I've modified a bit john's answer, this is how I fixed it
export class ViewAllProductsByCategoryComponent implements OnInit, OnDestroy {
searchCategory: any;
products: Product;
mySubscription: any;
constructor(private activatedRoute: ActivatedRoute,
private productsService: ProductsService,
private router: Router,
) {
this.router.routeReuseStrategy.shouldReuseRoute = () => {
return false;
};
this.mySubscription = this.router.events.subscribe((event) => {
if (event instanceof NavigationEnd) {
this.router.navigated = false;
}
});
}
ngOnInit(): void {
this.activatedRoute.queryParams.subscribe(res => {
this.searchCategory = res.name;
console.log(this.searchCategory);
});
this.productsService.searchCategoryProducts(this.searchCategory).subscribe(res => {
this.products = res;
console.log(this.products);
});
}
ngOnDestroy(): void {
if (this.mySubscription) {
this.mySubscription.unsubscribe();
}
}
}

Can't get deeper into the response data object in subscribe's callback function. Why?

I'm fetching data from RandomUser api with Angular HttpClient. I've created a method in a service calling GET, mapping and returning a Observable. Then I subscribe on this method in a component importing this service and in subscribe's callback I am trying to store the response data in a local variable. The problem is I can't get "deeper" into this response object than:
this.randomUser.getNew().subscribe(data => {
this.userData = data[0];
})
If I'm trying to reach any further element of that response object, and log it to console it I get "undefined". To be precise I cant reference to, for example:
this.randomUser.getNew().subscribe(data => {
this.userData = data[0].name.first;
})
If I store the "data[0]" in a variable first I can get into these unreachable properties. What is the reason of it? Please, help. Let me know what important piece of fundamental JS (or Angular) knowledge I'm not aware of. As far as I know I should be able to do what I am trying to do :)
service looks like these
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class RandomUserService {
url: string = " https://randomuser.me/api/ "
constructor(private http: HttpClient) { }
public getNew(): Observable<any> {
return this.http.get(this.url)
.pipe(map(responseData => {
const returnDataArray = [];
for (const key in responseData) {
returnDataArray.push(responseData[key])
}
return returnDataArray;
}))
}
}
component looks like these:
import { Component, OnInit } from '#angular/core';
import { RandomUserService } from 'src/app/shared/random-user.service';
import { Observable } from 'rxjs';
#Component({
selector: 'app-single-character',
templateUrl: './single-character.component.html',
styleUrls: ['./single-character.component.scss']
})
export class SingleCharacterComponent implements OnInit {
userData: object;
fname: string;
constructor(private randomUser: RandomUserService) {
this.randomUser.getNew().subscribe(data => {
this.userData = data[0];
})
}
ngOnInit(): void {
}
}
You are not parsing the returned data correctly in getNew().
The returned data looks like this:
So you need to access the user data like:
this.randomUser.getNew().subscribe(data => {
this.userData = data[0][0]; // note 2nd [0]
})
or for first name:
this.randomUser.getNew().subscribe(data => {
this.userData = data[0][0].name.first;
})
See stackblitz here: https://stackblitz.com/edit/so-http-parse?file=src/app/app.component.ts

Javascript push function

I want to create simple social media app.I'am working now on part with groups.But I cant filter only groups where some user is member.The code is following
import { Component, OnInit, OnChanges } from '#angular/core';
import { AngularFireDatabase } from '#angular/fire/database';
import { GroupsService } from '../groups.service';
#Component({
selector: 'app-groups',
templateUrl: './groups.component.html',
styleUrls: ['./groups.component.scss']
})
export class GroupsComponent implements OnInit {
uid = localStorage.getItem('uid')
groups: Array<any>;
mygroups: Array<any>;
sgroups;
constructor(private db: AngularFireDatabase, private _groups: GroupsService) {
}
ngOnInit() {
this._groups.getGroups().subscribe((data) => {
this.groups = data;
})
this.loadGroups()
}
search(e) {
this.sgroups = this.groups.find(gr => gr.name.toLowerCase().indexOf(e.target.value.toLowerCase()) > -1)
}
loadGroups() {
this.groups.map(gr => {
this._groups.getGroupMembers(gr.id).subscribe((data: any) => {
data.map(mem => {
if(mem.uid == this.uid) {
this.mygroups.push(gr); //here is the problem
}
})
})
})
}
scrollnav() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
}
Every help is welcomed.
Thanks a lot!
Problem is in initialization. intialize mygroups like
mygroups: any[] = [];
instead of
mygroups: Array<any>;
You can use forkJoin to fire all of the calls at once and get an array with all the results:
import {forkJoin} from 'rxjs';
...
const requests = this.groups.map(gr => this._groups.getGroupMembers(gr.id));
forkJoin(requests).subscribe((res) => this.mygroups = res);

How to get first value and then another subscribe method

I have developed a simple angular 7 web app. firebase database connectivity,
I am trying to store the first list in an array using the subscribe method and then console.log that array.
but before that data get the array will print undefined after some time it will get data.
How can code wait for the response is done and then print that array.
import { Injectable } from '#angular/core';
import { AngularFireList, AngularFireDatabase } from 'angularfire2/database';
#Injectable({
providedIn: 'root'
})
export class DressesService {
constructor(public firebase: AngularFireDatabase) { }
getJoinDresses(){
return this.firebase.list('makavana-tailor/dresses').snapshotChanges()
}
}
import { Component, OnInit } from '#angular/core';
import { DressesService } from '../../services/dresses/dresses.service';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
#Component({
selector: 'app-con-dress',
templateUrl: './con-dress.component.html',
styleUrls: ['./con-dress.component.css']
})
export class ConDressComponent implements OnInit {
constructor(private dresses: DressesService) { }
dressArray = [];
ngOnInit() {
this.getAllDresses();
console.log(this.dressArray)
}
getAllDresses(){
this.dresses.getJoinDresses().subscribe(actions => {
this.dressArray = actions.map(action => {
return {
$key: action.key,
...action.payload.val()
}
})
})
}
}
Your question title is not clear. But if I understand your problem correctly, you are facing an issue in working with asynchronous calls. Either you have to print console.log(this.dressArray) inside the subscribe or return the observable data from getAllDresses and subscribe to it within onInit()
code :
ngOnInit() {
this.getAllDresses().subscribe(data => {
this.dressArray = data;
console.log(this.dressArray)
});
}
getAllDresses(){
return this.dresses.getJoinDresses().pipe(map(actions => {
return actions.map(action => {
return {
$key: action.key,
...action.payload.val()
}
})
}))
}
The problem with your current code is that you show the array before it has a chance to be populated.
You know it's populated when the subscribe function is called.
So the easiest is to modify your code by moving the console.log inside the subscribe call:
ngOnInit() {
this.getAllDresses();
}
getAllDresses(){
this.dresses.getJoinDresses().subscribe(actions => {
this.dressArray = actions.map(action => ({
$key: action.key,
...action.payload.val()
}));
console.log(this.dressArray);
})
}

Angular 2 binding not updating after async operation

In my Angular 2 app, I want to start by loading a number of SVGs, before starting the app proper. To do this, I first load a list of svg locations from the server, then fetch each one in turn.
I have a 'loading' property on my AppComponent thats controlling a couple of ngIfs to show/hide some Loading text. Problem is, once the svgs are all loaded, Angular doesn't update the binding in AppComponent.
Why is this? I thought zones took care of this?
The SvgLoader
import {Injectable, Output, EventEmitter, NgZone} from 'angular2/core';
import {Http, Response} from 'angular2/http';
import 'rxjs/Rx';
import {Observable} from 'rxjs/Observable';
const SVG_LIST:string = 'svg/list.json';
#Injectable()
export class SvgLoader {
#Output() state: EventEmitter<string> = new EventEmitter();
private svgs:{[file:string]:string};
constructor(private http:Http){
this.svgs = {};
}
getSvg(path:string):string {
return this.svgs[path];
}
load():void {
this.http.get(SVG_LIST)
.map(res => {
return <Array<string>> res.json().files;
})
.flatMap((files) => Observable.forkJoin(files.map(file => {
return this.http.get('svg/' + file);
})))
.catch(this.handleError)
.mergeAll()
.subscribe(
res => {
let index = res.url.indexOf('svg');
let path = res.url.substring(index);
this.svgs[path] = res.text();
},
error => console.error(error),
() => {
this.state.emit('loaded');
}
);
}
private handleError(error:Response) {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
}
AppComponent
export class AppComponent {
// On start, list the game sessions
private state:string;
public loading:boolean;
constructor(private svgLoader:SvgLoader){
this.loading = true;
this.state = 'joining';
}
ngOnInit():void {
this.svgLoader.state.subscribe(this.loaded);
this.svgLoader.load();
}
loaded():void {
console.log('loaded');
this.loading = false;
}
}
The template
<div>
<h1 *ngIf="loading">Loading...</h1>
<div *ngIf="!loading">
Loaded
</div>
</div>

Categories

Resources