I appeal to the local Web Api at http: // localhost: 50806 / api / Users . It returns:
[ {"UserId":1,"Name":"O. Cole"}, {"UserId":2,"Name":"J. Shane"}, {"UserId":3,"Name":"V. Petrov"}, {"UserId":4,"Name":"M. Popov"} ] In the app folder there is a file user.ts
export class User{ UserId: number; Name: string; } File api access:
import {Injectable} from '@angular/core'; import {HttpClient} from '@angular/common/http'; @Injectable() export class HttpService{ Url = 'http://localhost:50806/'; constructor(private http: HttpClient){ } getUsers(){ return this.http.get(this.Url + 'api/Users'); } } Component file:
import { Component, OnInit} from '@angular/core'; import { HttpService} from './http.service'; import {User} from './user'; @Component({ selector: 'my-app', template: `<ul> <li *ngFor="let user of users"> <p>Имя пользователя: {{user?.Name}}</p> </li> </ul>`, providers: [HttpService] }) export class AppComponent implements OnInit { users: User[]; constructor(private httpService: HttpService){} ngOnInit(){ this.httpService.getUsers().subscribe((data: User[]) => this.users=data); } } The page is empty and there are no errors in the console, tell me what is wrong?
Update! The main module:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { HttpClientModule } from '@angular/common/http'; @NgModule({ imports: [ BrowserModule, FormsModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { }