Hey Ronald,

I think Jean Marc is true, you are writing  the observable object to the 
console when you do: 
console.log(this.userService.getUsers());

I you want to trace the users fetched from your backend you could do it in 
your service in the tap operator for instance:
tap(users => this.log('Fetched users, users')),

The interest of doing it here is that you will  see all the calls to your 
backend. Sometime there is more than you expect if you subscribe several 
times to your observable. In that case you can use an operator like 
ShareReplay.

In DisplayUsersComponent you can subscribe to the observable and store the 
array of users but I think that to avoid memory leak, you will have to 
store also the subscription in order to unsubscribe when the component is 
destroyed (ngOnDestroy hook).

Another solution would be to store only the observable in DisplayUsersCompo
nent:
users$: Observable<User[]> = this.userService.getUsers()

You can then use it in the template with the async pipe :
<clr-dg-row *ngFor="let user of users$ | async">

The async pipe will handle the subscription / unsubscrition for you.

Regards,
Arnaud.





On Tuesday, 7 January 2020 16:20:58 UTC+1, Ronald Faircloth wrote:
>
> Hey All,
>
> I am working on my first Angular project and I'm having a bit of trouble 
> with something.  I have a node.js backend with Express pulling data from an 
> MS SQL Server database.  I can display the data through the web browser 
> from the backend and I can see the JSON data being returned.  Next I 
> connected my endpoint and setup CORS for my local host.  I have a service 
> setup to pull the data from the endpoint.  I implement that service within 
> my component and if I print the data out to the console from within my 
> component I get the recordset.  The issue I am having is setting an array 
> from my endpoint data.  As I am very new to Angular I have tried following 
> the Heroes version which I could not get and then I tried a few other 
> versions as well that I came across online and none of them work.  When I 
> set my array equal to my observable and then print the array to the console 
> I get undefined.  Below is my code if anyone could be of assistance.
>
> User Class:
>
> export class User{
>     id: number;
>     ccn: string;
>     firstName: string;
>     lastName: string;
>     email: string;
> }
>
> User Service:
>
> import { Injectable } from '@angular/core';
> import { User } from './user';
> import { USERS } from './mock-users';
> import { MessageService } from './message.service';
> import { Observable, of } from 'rxjs';
> import { HttpClient, HttpHeaders } from '@angular/common/http';
> import { catchError, map, tap } from 'rxjs/operators';
>
> @Injectable({
>   providedIn: 'root'
> })
> export class UserService {
>
>   private userURL = 'api/users'
>   //private userURL = 'localhost:5000'
>
>   httpOptions = {
>     headers: new HttpHeaders({ 'Content-Type': 'application/json' })
>   };
>
>   constructor(
>     private http: HttpClient,
>     private messageService: MessageService) { }
>
>   //getUsers(): Observable<User[]> {
>   //  this.messageService.add('UserService: fetched users');
>   //  return of(USERS);
>   //}
>
>   /** GET users from the server */
>   getUsers(): Observable<User[]> {
>     //console.log('getting users');
>     return this.http.get<User[]>("http://localhost:5000/api/user";)
>       .pipe(
>         tap(_ => this.log('Fetched users')),
>         catchError(this.handleError<User[]>('getUsers', []))
>       );
>       //return this.http.get<User[]>("http://localhost:5000/api/user";);
>       //console.log('got users');
>   }
>
>   /* GET heroes whose name contains search term */
>   searchUsers(term: string): Observable<User[]> {
>     if (!term.trim()) {
>       // if not search term, return empty hero array.
>       return of([]);
>     }
>     return this.http.get<User[]>(`${this.userURL}/?ccn=${term}`).pipe(
>       tap(_ => this.log(`found users matching "${term}"`)),
>       catchError(this.handleError<User[]>('searchUsers', []))
>     );
>   }
>
>   addUser (user: User): Observable<User> {
>     return this.http.post<User>(this.userURL, user, this.httpOptions).pipe
> (
>       tap((newUser: User) => this.log(`added user w/ id=${newUser.id}`)),
>       catchError(this.handleError<User>('addUser'))
>     );
>   }
>
>   private handleError<T> (operation = 'operation', result?: T) {
>     return (error: any): Observable<T> => {
>       console.error(error);
>
>       this.log(`${operation} failed: ${error.message}`);
>
>       return of(result as T);
>     };
>   }
>
>   private log(message: string) {
>     this.messageService.add(`User service: ${message}`);
>   }
> }
>
> Display Users Component TS File:
>
> import { Component, OnInit } from '@angular/core';
> //import { USERS } from '../mock-users';
> import { UserService } from '../user.service';
> import { User } from '../user';
> import { Observable, of } from 'rxjs';
> import { catchError, map, tap } from 'rxjs/operators';
> import { element } from 'protractor';
>
> @Component({
>   selector: 'app-display-users',
>   templateUrl: './display-users.component.html',
>   styleUrls: ['./display-users.component.css']
> })
> export class DisplayUsersComponent implements OnInit {
>   users: User[] = [];
>
>   constructor(private userService: UserService) { }
>
>   //users$ = this.getUsers();
>
>   ngOnInit() {
>     this.getUsers();
>     console.log(this.userService.getUsers());
>     this.userService.getUsers().forEach(element => {
>       console.log(element);
>     });
>   }
>
>   getUsers(): void {
>     /*this.userService.getUsers()
>     .subscribe(users => this.users = users);*/
>     const userObservable = this.userService.getUsers();
>     userObservable.subscribe((userData: User[]) => {
>       this.users = userData;
>     });
>   }
>
> }
>
> Display Users Component HTML:
>
> <div class="clr-row">
>     <div class="clr-col-lg-11 clr-col-md-11 clr-col-11 main-div">
>         <div class="card card-style" style="box-shadow: 0 0 0 0;">
>             <div class="card-header">
>                 <h1><img src="../assets/images/BSOLOGO_gray.png" class=
> "title-img"><span class="title">&nbsp;&nbsp;Users</span></h1>
>             </div>
>             <div class="card-block">
>                 <div class="card-title">
>                     <clr-datagrid>
>                         <clr-dg-column>CCN</clr-dg-column>
>                         <clr-dg-column>Last Name</clr-dg-column>
>                         <clr-dg-column>First Name</clr-dg-column>
>                         <clr-dg-column>Email</clr-dg-column>
>                     
>                         <clr-dg-row *ngFor="let user of users">
>                             <clr-dg-cell>{{user.ccn}}</clr-dg-cell>
>                             <clr-dg-cell>{{user.lastName}}</clr-dg-cell>
>                             <clr-dg-cell>{{user.firstName}}</clr-dg-cell>
>                             <clr-dg-cell>{{user.email}}</clr-dg-cell>
>                         </clr-dg-row>
>                     
>                         <clr-dg-footer>{{users.length}} users</
> clr-dg-footer>
>                     </clr-datagrid>
>                 </div>
>             </div>
>         </div>
>     </div>
> </div>
>
> Any help would be greatly appreciated!
>
>
> Ronnie
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Angular and AngularJS discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/angular/badfad4b-3021-4b75-9063-300727a54630%40googlegroups.com.

Reply via email to