Angular 8: не удалось получить сообщение от Rest Api - PullRequest
1 голос
/ 28 июня 2019

Я использовал следующие ссылки https://grokonez.com/python/django-angular-6-example-django-rest-framework-mysql-crud-example-part-2-django-server и https://grokonez.com/frontend/django-angular-6-example-django-rest-framework-angular-crud-mysql-example-part-3-angular-client, чтобы создать API отдыха django и угловое приложение, которое вызывает этот отдых.

Учитывая, что я новичок в такого родаразвитие, поэтому я создал в качестве первого шага приложение, которое просто отображает список клиентов.Django rest API отлично работает.Я проверил это с помощью браузера:

enter image description here

Но моя проблема с угловым приложением, кажется, что оно не может получить сообщение с тем же URL:http://localhost:8000/customers Ниже мой угловой код:

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

import { AppRoutingModule, routingComponents } from './app-routing.module';
import { AppComponent } from './app.component';
import { CustomersListComponent } from './customers-list/customers-list.component';

@NgModule({
  declarations: [
    AppComponent,
    routingComponents,
    CustomersListComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { CustomersListComponent } from './customers-list/customers-list.component';

const routes: Routes = [
    { path: 'customers', component: CustomersListComponent },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

customer.ts

export class Customer {
    id: number;
    name: string;
    age: number;
    active: boolean;
}

customer.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class CustomerService {
    private baseUrl = 'http://localhost:8000/customers';

    constructor(private http: HttpClient) { }

    getCustomersList(): Observable<any> {
        return this.http.get(`${this.baseUrl}/`);
    }

}

Customers-list.component.ts

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

import { CustomerService } from '../customer.service';
import { Customer } from '../customer';

@Component({
  selector: 'app-customers-list',
  templateUrl: './customers-list.component.html',
  styleUrls: ['./customers-list.component.css']
})
export class CustomersListComponent implements OnInit {

    customers: Observable<Customer[]>;


    constructor(private customerService: CustomerService) { }

    ngOnInit() {
        console.log("Hellllllllo from customers-list.component.ts ngOnInit");
         this.reloadData();
    }

    reloadData() {
        this.customers= this.customerService.getCustomersList();
    }

}

Customers-list.component.html

<h1>Customers {{JSON.stringify(this.customers)}}</h1>

<div *ngFor="let customer of customers" style="width: 300px;">
    <h2>Hello iii</h2>
    <div>
    <label>Name: </label> {{customer.name}}
  </div>
  <div>
    <label>Age: </label> {{customer.age}}
  </div>
  <div>
    <label>Active: </label> {{customer.active}}
  </div>
</div>

Результат, полученный при звонке / клиентамиз браузера следующее:

enter image description here

Сообщение «Маршрутизация и навигация» приходит с app.component.html. Как вы видите сообщение «Клиенты отображаются»но все, что соответствует переменным клиентам (то есть списку клиентов), не отображается.

Кто-то знает, что является основной причиной этой проблемы?и как я могу это исправить?Заранее спасибо

Ответы [ 2 ]

0 голосов
/ 28 июня 2019

К вашим услугам

getCustomersList(): Observable<any> {
        return this.http.get(`${this.baseUrl}/`);
    }

Эта функция возвращает наблюдаемую Таким образом, вы должны подписаться на это, чтобы сделать запрос

 this.customerService.getCustomersList().subscribe((res: any) => {
       this.customers = res;
   });

Или в вашем html-файле вы можете добавить асинхронный канал, как этот

*ngFor="let customer of customers | async
0 голосов
/ 28 июня 2019

Вы должны subscribe получить ответ от API, потому что http.get возвращает наблюдаемые, наблюдаемые вызовы, только когда вы подписаны на него.попробуйте следующий метод

 reloadData() {
   this.customerService.getCustomersList().subscribe((res: any) => {
       this.customers = res;
   });
 }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...