почему мой Angular сервис (который включает httpClient) в constructer ломает модуль? - PullRequest
0 голосов
/ 21 октября 2019

Итак, в основном я создал бэкэнд RESTful API, и я пытаюсь получить к нему доступ.

Таким образом, я создал database-connection.service для публикации.

У меня проблемы с его реализацией.

Ниже приведен мой код. Если проблема найдена и объяснена, она будет оценена ...

+ app
|- app-routing.module.ts
|- app.component.css
|- app.component.html
|- app.component.spec.ts
|- app.component.ts
|- app.module.ts
|-+ homepage
  |- homepage-routing.module.ts
  |- homepage.module.ts
  |-+ spelling-app
    |- database-connection.service.ts
    |- database-connection.service.spec.ts
    |- spelling-app.module.ts
    |- user.model.ts
    |-+ intro-page
      |- intro-page.component.ts
      |- intro-page.component.css
      |- intro-page.component.html
      |- intro-page.component.spec.ts

spelling-app.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { SpellingAppRoutingModule } from './spelling-app-routing.module';
import { IntroPageComponent } from './intro-page/intro-page.component';

import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    CommonModule,
    SpellingAppRoutingModule,
    FormsModule,
    HttpClientModule
  ],
  declarations: [IntroPageComponent]
})
export class SpellingAppModule { }

database-connection.service.ts

import { Injectable } from '@angular/core';

import { HttpClient, HttpHeaders } from '@angular/common/http';

import { User } from './user.model';

import { Observable } from 'rxjs';

@Injectable()
export class DatabaseConnectionService {

  constructor(private http:HttpClient) { }


  private httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/json' })
  };

  public addUser(user: User): Observable<User> {
    return this.http.post<User>('http://localhost:8081/add-user', user, this.httpOptions)
  }

}

intro-page.component.ts

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

import { User } from '../user.model';

import { DatabaseConnectionService } from '../database-connection.service';


@Component({
  selector: 'app-intro-page',
  templateUrl: './intro-page.component.html',
  styleUrls: ['./intro-page.component.css']
})

export class IntroPageComponent implements OnInit {

  public results:any;
  private user = new User();

  constructor(
    private DatabaseConnectionService: DatabaseConnectionService
  ) { }

  ngOnInit() { }

  callpost() {
    this.results = this.DatabaseConnectionService.addUser(this.user);
  }

}

1 Ответ

0 голосов
/ 21 октября 2019

Вам необходимо добавить «провайдеров» в ваш модуль сервиса. Убедитесь, что ваш угол обновлен, и поставщики приняты.

@NgModule({
  imports: [
  ...
  ],
  declarations: [...],
  providers:[DatabaseConnectionService]
})

Или используйте инъекцию в вашем сервисе

@Injectable({
  providedIn: 'root', //or providerIn:YourModule
})

Вам также необходимо добавить HttpClientModule в app.module.ts не в другом модуле.

Также за наблюдаемой должна следовать операция;

this.results.toPromise().then(...).catch(...)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...