Я запустил angular два дня назад, я пытаюсь создать службу, которая будет выполнять запрос на получение по моей конечной точке восстановления загрузки Spring, и я хочу отобразить результат в моем приложении angular
Вот что я пробовал до сих пор
Моя служба:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { ITweet } from './itweet';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ReactiveTwitterService {
constructor(private http_client: HttpClient, private tweetTag: string) { }
spring_webflux_service_url = 'http://localhost:8081/search';
myTweets: Observable<ITweet[]>;
setTweetTag(tag) {
this.tweetTag = tag;
}
seearchTweets() {
this.myTweets = this.http_client.get<ITweet[]>(this.spring_webflux_service_url + '/' + this.tweetTag);
}
getTweets() {
return this.myTweets;
}
}
Как вы видите, я жду твитов в качестве ответа, так что вот мой интерфейс твитов.
export interface ITweet {
id: {
text: string,
name: string
};
tag: string;
}
Мой модуль приложения выглядит так
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {HttpClientModule} from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { SerachBarComponent } from './serach-bar/serach-bar.component';
import { SearchReasultComponent } from './search-reasult/search-reasult.component';
import { HeaderComponent } from './header/header.component';
import { ResultItemComponent } from './result-item/result-item.component';
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
SerachBarComponent,
SearchReasultComponent,
ResultItemComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Я погуглил, что нет необходимости настраивать мой сервис в провайдерах благодаря Предоставляется в директиве в реализации сервиса
Компоненты, в которых я использую эту услугу
import { Component, HostListener } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
innerWidth: number;
styleClass = {
wide_screen: 'w3-light-grey',
break_point: 'w3-dark-grey'
};
@HostListener('window:resize', ['$event'])
onResize(event) {
this.innerWidth = window.innerWidth;
}
getStyle() {
return (innerWidth > 769) ? this.styleClass.wide_screen : this.styleClass.break_point;
}
}
И
import { Component, OnInit, HostListener } from '@angular/core';
import { ReactiveTwitterService } from '../reactive-twitter.service';
@Component({
selector: 'app-serach-bar',
templateUrl: './serach-bar.component.html',
styleUrls: ['./serach-bar.component.css']
})
export class SerachBarComponent implements OnInit {
innerWidth: number;
constructor(private twiterService: ReactiveTwitterService) { }
placeholder = 'search';
styleClass = {
wide_screen: 'w3-input w3-light-grey',
break_point: 'w3-input w3-white'
};
doSearch(tag) {
this.twiterService.setTweetTag(tag);
this.twiterService.seearchTweets();
}
ngOnInit() {
}
@HostListener('window:resize', ['$event'])
onResize(event) {
this.innerWidth = window.innerWidth;
}
getStyle() {
return (innerWidth > 769) ? this.styleClass.wide_screen : this.styleClass.break_point;
}
}
И
import { Component, OnInit, HostListener } from '@angular/core';
import { ReactiveTwitterService } from '../reactive-twitter.service';
import { ITweet } from '../itweet';
@Component({
selector: 'app-search-reasult',
templateUrl: './search-reasult.component.html',
styleUrls: ['./search-reasult.component.css']
})
export class SearchReasultComponent implements OnInit {
search_result: ITweet[];
innerWidth: number;
constructor(private _twitterService: ReactiveTwitterService) { }
styleClass = {
wide_screen: 'w3-ul w3-hoverable',
break_point: 'w3-green w3-container'
};
ngOnInit() {
this._twitterService.getTweets().subscribe(tweet => this.search_result = tweet);
}
is_search_result_empty() {
return this.search_result === [];
}
set_search_result_empty() {
this.search_result = [];
}
@HostListener('window:resize', ['$event'])
onResize(event) {
this.innerWidth = window.innerWidth;
}
get_list_style() {
return (innerWidth > 769) ? this.styleClass.wide_screen : this.styleClass.break_point;
}
}
Мои шаблоны
AppComponent
<div class = "{{getStyle()}}" style = "width: 100%;height: 100%;">
<app-header></app-header>
<app-serach-bar></app-serach-bar>
<app-search-reasult></app-search-reasult>
</div>
Панель поиска
<div class = "w3-container w3-margin-top">
<input class = "{{getStyle()}}" type = "text" placeholder = "{{placeholder}}" (onclick.enter) = "doSearch(searchinput.value)" #searchinput>
</div>
Результат поиска
<div class = "w3-container" *ngIf = "!is_search_result_empty">
<ul class = "{{get_list_style()}}">
<app-result-item *ngFor = "let current_item of search_result; trackBy:current_item.id" [item] = "current_item"></app-result-item>
</ul>
</div>
консоль регистрирует исключение, и все пустое
Что мне делать, чтобы это исправить?



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


вам нужно добавить службу к поставщикам в модуле, конечно, не забудьте импортировать службу
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
SerachBarComponent,
SearchReasultComponent,
ResultItemComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
FormsModule
],
providers: [
ReactiveTwitterService
],
bootstrap: [AppComponent]
})
в вашем коде constructor(private _twitterService: ReactiveTwitterService) { } нет способа инициализировать private tweetTag: string, поэтому он все равно не работает, и @Injectable({ providedIn: 'root' }) не действует так же, как providers: [ReactiveTwitterService]
Вы пытались перезапустить сервер после обновления, я имею в виду, что вам нужно повторно запустить ng serve, я уверен, что это решит вашу проблему
кроме того, вам нужно удалить private tweetTag: string из конструктора службы и создать для него функцию установки, поэтому он все еще показывает ошибку
в вашем коде constructor(private _twitterService: ReactiveTwitterService) { } нет способа инициализировать private tweetTag: string, поэтому он все равно не работает, и @Injectable({ providedIn: 'root' }) не действует так же, как providers: [ReactiveTwitterService]
Ваш сервис должен быть доступен вашему компоненту или модулю как поставщику.
Вы можете добавить его в массив providers: в appmodule или в отдельный модуль и вставить в компонент для использования.
Я уже пробовал это, но та же проблема, и это больше не является обязательным из-за использования @Injectable ({providedIn: 'root'})
Я уже пробовал это, но та же проблема, и это больше не является обязательным из-за использования @Injectable ({providedIn: 'root'})