简体   繁体   English

Angular 6服务注入异常

[英]Angular 6 service injection exception

I started angular two days ago, im 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 我的app模块看起来像这样

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 我用谷歌搜索,由于服务实现中的providedIn指令 ,不需要在提供程序中设置我的服务

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 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] 在您的代码constructor(private _twitterService: ReactiveTwitterService) { }中无法初始化private tweetTag: string因此它仍然失败,并且@Injectable({ providedIn: 'root' })providers: [ReactiveTwitterService]行为不同providers: [ReactiveTwitterService]

Your service should be made available to your component or the module as a provider. 您的服务应作为提供商提供给您的组件或模块。 You can add it to providers: array at appmodule or to the individual module and inject it in component for use. 您可以将它添加到providers: appmodule中的数组或单个模块,并将其注入组件以供使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM