Angular 6 服务注入异常 [英] Angular 6 service injection exception
问题描述
我两天前开始使用 angular,我正在尝试创建一个服务,该服务将对我的 Spring Boot Rest 端点执行 get 请求,并且我希望在我的 angular 应用程序中显示结果
这是我迄今为止所尝试的
我的服务:
import { Injectable } from '@angular/core';从'@angular/common/http' 导入 { HttpClient };从 './itweet' 导入 { ITweet };从 'rxjs' 导入 { Observable };@Injectable({提供在:'根'})导出类 ReactiveTwitterService {构造函数(私有http_client:HttpClient,私有tweetTag:字符串){}spring_webflux_service_url = 'http://localhost:8081/search';myTweets: Observable;setTweetTag(标签){this.tweetTag = 标签;}seearchTweets() {this.myTweets = this.http_client.get<ITweet[]>(this.spring_webflux_service_url + '/' + this.tweetTag);}获取推文(){返回 this.myTweets;}}
如你所见,我正在等待推文作为回应,所以这是我的推文界面
导出接口 ITweet {ID: {文本:字符串,名称:字符串};标签:字符串;}
我的应用模块看起来像这样
import { BrowserModule } from '@angular/platform-browser';从'@angular/core' 导入 { NgModule };从 '@angular/common/http' 导入 {HttpClientModule};从'@angular/forms'导入{FormsModule};import { AppRoutingModule } from './app-routing.module';从 './app.component' 导入 { AppComponent };从 './serach-bar/serach-bar.component' 导入 { SerachBarComponent };import { SearchReaultComponent } from './search-reasult/search-reasult.component';import { HeaderComponent } from './header/header.component';从 './result-item/result-item.component' 导入 { ResultItemComponent };@NgModule({声明: [应用组件,标题组件,SerachBarComponent,搜索结果组件,结果项组件],进口:[浏览器模块,应用路由模块,HttpClient 模块,表单模块],提供者:[],引导程序:[AppComponent]})导出类 AppModule { }
我在 google 上搜索到,由于服务实现中的 providedIn 指令
我使用此服务的组件
import { Component, HostListener } from '@angular/core';@成分({选择器:'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.css']})导出类 AppComponent {内部宽度:数量;样式类 = {宽屏:'w3-浅灰色',断点:'w3-深灰色'};@HostListener('window:resize', ['$event'])onResize(事件){this.innerWidth = window.innerWidth;}获取样式(){返回 (innerWidth > 769) ?this.styleClass.wide_screen : this.styleClass.break_point;}}
AND
import { Component, OnInit, HostListener } from '@angular/core';从 '../reactive-twitter.service' 导入 { ReactiveTwitterService };@成分({选择器:'app-serach-bar',templateUrl: './serach-bar.component.html',styleUrls: ['./serach-bar.component.css']})导出类 SerachBarComponent 实现 OnInit {内部宽度:数量;构造函数(私人推特服务:ReactiveTwitterService){}占位符 = '搜索';样式类 = {Wide_screen: 'w3-input w3-light-grey',break_point: 'w3-input w3-white'};doSearch(标签){this.twiterService.setTweetTag(tag);this.twiterService.seearchTweets();}ngOnInit() {}@HostListener('window:resize', ['$event'])onResize(事件){this.innerWidth = window.innerWidth;}获取样式(){返回 (innerWidth > 769) ?this.styleClass.wide_screen : this.styleClass.break_point;}}
AND
import { Component, OnInit, HostListener } from '@angular/core';从 '../reactive-twitter.service' 导入 { ReactiveTwitterService };从 '../itweet' 导入 { ITweet };@成分({选择器:应用搜索结果",templateUrl: './search-reasult.component.html',styleUrls: ['./search-reasult.component.css']})导出类 SearchReaultComponent 实现 OnInit {search_result: ITweet[];内部宽度:数量;构造函数(私有_twitterService:ReactiveTwitterService){}样式类 = {宽屏:'w3-ul w3-hoverable',break_point: 'w3-green w3-container'};ngOnInit() {this._twitterService.getTweets().subscribe(tweet => this.search_result = tweet);}is_search_result_empty() {返回 this.search_result === [];}set_search_result_empty() {this.search_result = [];}@HostListener('window:resize', ['$event'])onResize(事件){this.innerWidth = window.innerWidth;}get_list_style() {返回 (innerWidth > 769) ?this.styleClass.wide_screen : this.styleClass.break_point;}}
我的模板是
应用组件
<app-header></app-header><app-serach-bar></app-serach-bar><应用搜索结果></应用搜索结果>
搜索栏
<input class="{{getStyle()}}" type="text" placeholder="{{placeholder}}" (onclick.enter)="doSearch(searchinput.value)" #searchinput>
搜索结果
<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>
控制台记录异常,一切都是空白
我该怎么做才能解决这个问题??
需要在模块中添加服务到provider当然记得导入服务
@NgModule({声明: [应用组件,标题组件,SerachBarComponent,搜索结果组件,结果项组件],进口:[浏览器模块,应用路由模块,HttpClient 模块,表单模块],供应商: [响应式推特服务],引导程序:[AppComponent]})
在您的代码中 constructor(private _twitterService: ReactiveTwitterService) { }
没有办法初始化 private tweetTag: string
因此它仍然失败,并且 @Injectable({ providedIn: 'root' })
与 providers: [ReactiveTwitterService]
I started angular two days ago, i m trying to create a service that will do a get request over my spring boot rest end point and I wish to display the result in my angular app
Here is what i have tried till now
My Service:
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;
}
}
As you see I m waiting for tweets as a response so here is My tweet Interface
export interface ITweet {
id: {
text: string,
name: string
};
tag: string;
}
My app module is looking like this
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 { }
I googled that there is no need for setting my service in providers thanks to providedIn directive in the service implementation
The components where i use this service
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;
}
}
AND
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;
}
}
AND
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;
}
}
My templates are
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>
SearchBar
<div class="w3-container w3-margin-top">
<input class="{{getStyle()}}" type="text" placeholder="{{placeholder}}" (onclick.enter)="doSearch(searchinput.value)" #searchinput>
</div>
Search Result
<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>
the console log an exception and everything is blank
What should i do to fix this ??
you need to add the service to the providers in the module of course remember to import the service
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
SerachBarComponent,
SearchReasultComponent,
ResultItemComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
FormsModule
],
providers: [
ReactiveTwitterService
],
bootstrap: [AppComponent]
})
in your code constructor(private _twitterService: ReactiveTwitterService) { }
there is no way to initialize the private tweetTag: string
therefore it still fail, and the @Injectable({ providedIn: 'root' })
does not act the same as providers: [ReactiveTwitterService]
这篇关于Angular 6 服务注入异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!