Search code examples
javascriptangularcomponents

Why is my Angular Service not assigning a filtered result to my property?


I setup a service called 'bankService' which is being used by my 'user' component. The 'user' component is receiving the data from the service correctly but I am unable to assign a filtered result to my 'currentAccount' property. I am filtering by 'id' from the list of 'accounts' that is being returned from my service. Any help with an explanation would be appreciated!

Model

export interface Account {
  id: number;
  accountHolder: string;
  checking: number;
  savings: number;
}

Service

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { elementAt, Observable } from 'rxjs';
import { Account } from '../models/Account';
import { Transaction } from '../models/Transaction';

@Injectable({
  providedIn: 'root',
})
export class BankServiceService {
  private apiUrl = 'http://localhost:5000/accounts';

  constructor(private http: HttpClient) {}

  getAccounts(): Observable<Account[]> {
    return this.http.get<Account[]>(this.apiUrl);
  }
}

Component

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Account } from 'src/app/models/Account';
import { BankServiceService } from 'src/app/services/bank-service.service';

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css'],
})
export class UserComponent implements OnInit {
  currentAccount: Account[] = [];
  accountId: number;
  accountHolder: string;
  checkingAmount: number;
  savingsAmount: number;

  constructor(
    private route: ActivatedRoute,
    private bankService: BankServiceService
  ) {}

  ngOnInit(): void {
    // gets the parameter for the url (the param is the account id)
    this.accountId = this.route.snapshot.params['id'];
    console.log('id: ', this.accountId);

    // pulls in all accounts
    this.bankService
      .getAccounts()
      .subscribe(
        (accounts) =>
          (this.currentAccount = accounts.filter(
            (account) => account.id === this.accountId
          ))
      );

    console.log('current account: ', this.currentAccount);
  }
}

Solution

  • If I'm not mistaking, your issue is this one:

    • the account id received from the backend is a number
    • the account id pulled from the url is a string

    In the filter function you are using strict equality, and that's why no account id passes the condition in the filter callback

    You can switch from strict equality to loose equality (==) or do something like this for the filter callback:

    (account) => account.id.toString() === this.accountId