N
N
Nozim Y2017-04-03 21:40:36
JavaScript
Nozim Y, 2017-04-03 21:40:36

Instead of a json object - undefined. Anguar 2 and 4, how do you communicate via RestAPI?

In short: there is no way to exchange json between Angular and nodejs. Those. accept json via http in angular'e. The ng http tutorials show how to work with the backend stub, and this code (of course - that important selected part, not all) does not work with the real API.
Here is the component and service where the action happens:
app.component.ts

import { Component, OnInit } from '@angular/core';

import { User } from './user';
import { UsersService } from './users.service';

console.log('console.log');
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit{
  title = 'Title';
  
  //users: User[];
  
  // getUsers(): void {
  //   this.usersService.getUsers().then(users => this.users = users);
  // }
  
  // ngOnInit(): void {
  //   this.getUsers();
  //   console.log(this.users);
  // }
  
  constructor( private usersService: UsersService  ) {}
  
  errorMessage: string;
  users: User[];
  mode = 'Observable';
  
  ngOnInit() { this.getUsers(); }
  
  getUsers() {
    this.usersService.getUsers()
                    .subscribe(
                      users => this.users = users,
                      error =>  this.errorMessage = <any>error);
  console.log("appComponent.users:  "+this.users);
  }
}

users.service.ts
import { Injectable } from '@angular/core';
import { Headers, Http, Response  } from '@angular/http';

import 'rxjs/add/operator/toPromise';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

import { User } from './user';

@Injectable()
export class UsersService {
  private usersUrl = '***.****.io/api/users';  // URL to web api

  
  constructor(private http: Http) { }
  
  getUsers(): Observable<User[]> {
    return this.http.get(this.usersUrl)
                    .map(this.extractData)
                    .catch(this.handleError);
  }
  private extractData(res: Response) {
    let body = res.json();
    console.log("usersService body:  "+body);
    return body.data || { };
  }
  
  private handleError (error: Response | any) {
    // In a real world app, you might use a remote logging infrastructure
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
  }
    
    // getUsers(): Promise<User[]> {
    //   return this.http.get(this.usersUrl)
    //             .toPromise()
    //             .then(response => response.json().data as User[])
    //             .catch(this.handleError);
    // }
    
    // private handleError(error: any): Promise<any> {
    //   console.error('An error occurred', error); // for demo purposes only
    //   return Promise.reject(error.message || error);
    // }
    
    
    
    //!!!
    // getUser(limit: number): Promise<User> {
    //   const url = `${this.userUrl}/${limit}`;
    //   return this.http.get(url)
    //     .toPromise()
    //     .then(response => response.json().data as User)
    //     .catch(this.handleError);
        
    // }
    
    // private headers = new Headers({'Content-Type': 'application/json'});

    // update(user: User): Promise<User> {
    //   const url = `${this.userUrl}/${user.id}`;
    //   return this.http
    //     .put(url, JSON.stringify(user), {headers: this.headers})
    //     .toPromise()
    //     .then(() => user)
    //     .catch(this.handleError);
    // }
    
    // create(name: string): Promise<User> {
    //   return this.http
    //     .post(this.userUrl, JSON.stringify({name: name}), {headers: this.headers})
    //     .toPromise()
    //     .then(res => res.json().data as User)
    //     .catch(this.handleError);
    // }
    
    // delete(id: number): Promise<void> {
    //   const url = `${this.userUrl}/${id}`;
    //   return this.http.delete(url, {headers: this.headers})
    //     .toPromise()
    //     .then(() => null)
    //     .catch(this.handleError);
    // }
}

7e1539e9bf124aec9f26496866db1295.PNG1736737fde6047ef96139a494ea6ce42.PNG
I ask the experienced to point the right direction to the beginner in particular in Angular'e.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Zuev, 2017-04-03
@NozimY

This code here gives you an array in the console. Then, for some reason, you write the array has no property , so your service returns an empty object. Remove this line altogether, no one receives data from an asynchronous request in this way

this.usersService.getUsers()
    .subscribe(
        users => {
           console.log(users);
           this.users = users;
        },
        error =>  this.errorMessage = <any>error);

Total
private extractData(res: Response) {
    return res.json() || [];
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question