Struggling to make observables work has been quite the challenge for me lately.
My code now resembles a chaotic battleground rather than the organized structure it once was.
The dreaded "ERROR TypeError: Cannot read property 'map' of undefined" keeps haunting me.
I've been attempting to import JSON data (which succeeds), filter out the active members (which works), sort them alphabetically (which fails), and create a unique list based on the "team" column (also failing).
This is how my service looks:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
//import 'rxjs/add/operator/catch';
//import 'rxjs/add/operator/map';
import { catchError, map, tap } from 'rxjs/operators';
import { Member } from '../class/member';
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Injectable()
export class UserinfoService
{
//constructor
constructor(private http: HttpClient)
{
}
//methods or services
getMembers(): Observable<Member[]>
{
return this.http.get<Member[]>('http://datalocation.com/JsonData/api/teammembers');
}
}
And here's the component:
import { Component, OnInit, Injectable } from '@angular/core';
import { UserinfoService } from '../services/userinfo.service';
import { Member } from '../class/member';
import { MatDialog } from '@angular/material';
import { MemberdialogComponent } from '../memberdialog/memberdialog.component';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { catchError, map, tap } from 'rxjs/operators';
// import 'rxjs/Rx'; // adds ALL RxJS statics & operators to Observable
// Statics
import 'rxjs/add/observable/throw';
// Operators
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/toPromise';
@Component({
selector: 'app-teammembers',
templateUrl: './teammembers.component.html',
styleUrls: ['./teammembers.component.css']
})
export class TeammembersComponent implements OnInit
{
//props
teamMembers: any[];
searchQuery: any = "";
searchResults: any[] = this.teamMembers;
teams: any[];
selectedTeam: any;
//constructor
constructor(private userinfoService: UserinfoService, public dialog: MatDialog)
{
//getData
userinfoService.getMembers().subscribe(teamMembers => this.teamMembers = teamMembers
.filter(member => member.isActive)
.sort((a, b) => a.lastName.localeCompare(b.lastName)));
//put all information in results
this.searchResults = this.teamMembers;
//getTeams
this.teams = this.teamMembers
.map(item => item.team)
.filter((value, index, self) => self.indexOf(value) === index)
}
If anyone can offer some guidance, I would truly appreciate it. I had everything running smoothly when it was just a simple service, but as soon as I introduced observables, chaos ensued.