component can't find provider from lazy-loaded module - javascript

I have a lazy-loaded module which has one service and one component.
I would like to use the service in that component but I get:
Error: No provider for EventService!
The module
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { EventRoutingModule } from './event-routing.module';
import { FormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import { EventListModule } from './../event-list/event-list.module';
import { ModuleWithProviders } from '#angular/core';
import { EventComponent } from './event.component';
import { EventService } from './event.service';
#NgModule({
imports: [
CommonModule,
FormsModule,
HttpModule,
EventRoutingModule,
EventListModule
],
declarations: [EventComponent]
})
export class EventModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: EventModule,
providers: [EventService]
};
}
}
the component
import { Component, OnInit } from '#angular/core';
import { EventService } from './event.service';
#Component({
templateUrl: './event.component.html',
styleUrls: ['./event.component.scss']
})
export class EventComponent implements OnInit {
private eventService: EventService;
constructor(eventService: EventService) {
this.eventService = eventService;
}
ngOnInit() {
this.eventService.getEvents().subscribe(data => console.log(data), error => console.log(error));
}
}
the service
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs/Observable';
import { AuthHttp } from 'angular2-jwt';
#Injectable()
export class EventService {
private static readonly URL = 'http://localhost:3000/api/events';
constructor(private authHttp: AuthHttp) { }
public getEvents() {
return this.authHttp.get(EventService.URL);
}
}
I have looked at a couple of posts here but havent been able to get a solution from them.
I know providers in lazy-loaded modules are module-scoped and lazy-loaded modules have their own dependency tree.
But it must be possible to inject the provider into the component, mustn't it?

You need to define how you provide your service.
You can define how it is provided at the module level:
#NgModule({
imports: [
CommonModule,
FormsModule,
HttpModule,
EventRoutingModule,
EventListModule
],
declarations: [EventComponent],
providers: [EventService]
})
export class EventModule { ... }
This means that one EventService instance will be available for the whole module.
Or at the component level:
#Component({
templateUrl: './event.component.html',
styleUrls: ['./event.component.scss'],
providers [EventService]
})
export class EventComponent implements OnInit { ... }
This means that one EventService instance will be available for each component instance. This is due to the hierarchical injectors feature. The component defines its own injector which can hold its own instances that are being made available to its children.
[EventService] is equivalent to [ { provide: EventService, useClass: EventService }]. Which means that the key used to inject the dependency is EventService and the instance is being constructed by using the EventService constructor.

Related

Service not found in NativeScript Angular

I am new to Angular nativescript, I created a service using the "ng generate service" command in my native angular application, but when importing the service I get the error that the module cannot be found
app.module.ts
import { NgModule, NO_ERRORS_SCHEMA } from "#angular/core";
import { NativeScriptModule, NativeScriptHttpClientModule } from "#nativescript/angular";
import { AppRoutingModule } from "./app-routing.module";
import { AppComponent } from "./app.component";
import { LoginComponent } from './components/login/login.component';
#NgModule({
bootstrap: [
AppComponent
],
imports: [
NativeScriptModule,
AppRoutingModule,
NativeScriptHttpClientModule
],
declarations: [
AppComponent,
LoginComponent,
],
providers: [],
schemas: [
NO_ERRORS_SCHEMA
]
})
/*
Pass your application module to the bootstrapModule function located in main.ts to start your app
*/
export class AppModule { }
ApiBackRequestService.ts
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '#angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { environment } from '../environments/environment';
#Injectable({
providedIn: 'root'
})
export class ApiBackRequestService {
constructor(
private http: HttpClient) {
}
}
Login.component.ts
import { Component, OnInit } from '#angular/core';
import { ApiBackRequestService } from 'src/app/services/api-back-request.service';
#Component({
selector: 'ns-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
pokemon = [];
constructor(private api: ApiBackRequestService) { }
ngOnInit(): void {
}
}
Thanks
Is it a code-sharing project? in the Login.component.ts file just add # before the src.
change
import { ApiBackRequestService } from 'src/app/services/api-back-request.service';
to
import { ApiBackRequestService } from '#src/app/services/api-back-request.service';
this solved my problem
import { ApiBackRequestService } from '../../services/api-back-request.service';

Custom components are not known elements in Angular CLI app

I am looking at learning Angular 8 with the Angular CLI.
I have added two new components to a core module which i have then imported to the app module.
When I try to render the components in my app html the 'not known element' error is thrown in the console.
I am unsure as to why?
Here is my app.module.ts
import { BrowserModule } from "#angular/platform-browser";
import { NgModule } from "#angular/core";
import { AppComponent } from "./app.component";
import { NoopAnimationsModule } from "#angular/platform-browser/animations";
import { CoreModule } from "./core/core.module";
#NgModule({
declarations: [AppComponent],
imports: [BrowserModule, NoopAnimationsModule, CoreModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
My core.module.ts
import { NgModule } from "#angular/core";
import { CommonModule } from "#angular/common";
import { InputComponent } from "../input/input.component";
import { GraphComponent } from "../graph/graph.component";
#NgModule({
declarations: [InputComponent, GraphComponent],
imports: [CommonModule],
exports: [InputComponent, GraphComponent]
})
export class CoreModule {}
app.component.html
<div>
<InputComponent></InputComponent>
<GraphComponent></GraphComponent>
</div>
And an example of one of the custom components:
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-input',
templateUrl: './input.component.html',
styleUrls: ['./input.component.scss']
})
export class InputComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
I just realised that I am not referring to the components with the correct selectors!
I should be using: app-input & app-graph in the app.component.html.

Emit events between nested components grandchild to root component

I have wheels.component nested to car.component.
wheels.component:
export class WheelsComponent {
#Output() onLoaded : EventEmitter<string>() = new EventEmitter<string>();
private downloadAllFiles(url: string) {
this.onLoaded.emit('Hello, World 1!');
//some operations to wait
this.onLoaded.emit('Hello, World 2!');
};
}
Component car.component is not written at html page, but called through routing at car-routing.module.ts:
#NgModule({
imports: [
RouterModule.forChild([
{
path: 'sfactmessage/:id',
component: CarComponent,
resolve: {
card: cardResolver
}
}
])
],
exports: [RouterModule]
})
export class CarRoutingModule {}
What I want is to handle event emitted from wheels.component, not at car.component, but at app.component.
Is it possible to handle event at app.component?
The plunker sample is not working (sorry, this is my first plunkr example), but gives a view how my app is arranged.
Hello_ friend.
So basically if you want to use events globally in your application you can use a Service in combination with EventEmitter
In this case you create a service for example car.service.ts
import { Injectable, EventEmitter } from '#angular/core';
#Injectable()
export class CarService {
onLoaded : EventEmitter<string> = new EventEmitter<string>();
}
Then use this service in a child component to emit events like this wheels.component.ts
import { Component, EventEmitter } from '#angular/core';
import { CarService } from './car.service';
#Component({
selector: 'wheels',
template: '<a (click)="sendValues()"> Click me to send value </a>'
})
export class WheelsComponent {
constructor(private carService:CarService ){}
sendValues() {
/* Use service to emit events that can be used everywhere in the application */
this.carService.onLoaded.emit('Button in WheelsComponent was clicked ...');
};
}
and then capture this event from AppComponent for example app.component.ts
import { Component, OnInit, OnDestroy } from '#angular/core';
import { CarService } from './cars/car.service';
import { Subscription } from 'rxjs';
#Component({
selector: 'my-app',
templateUrl: `src/app.component.html`
})
export class AppComponent implements OnInit, OnDestroy{
private subscription: Subscription;
private loading = true;
name = 'Angular';
constructor(private carService: CarService){}
ngOnInit(){
this.subscription = this.carService.onLoaded.subscribe((message) => {
/*
Here you receive events from anywhere where
carService.onLoaded.emit() is used
**/
alert(`From AppComponent -> ${message}`);
});
}
ngOnDestroy(){
/* Don't forget to unsubscribe when component is destroyed */
this.subscription.unsubscribe();
}
}
I M P O R T A N T______________
If you want your service to work globally you need to declare it in the top level providers for example app.module.ts is a good place:
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { AppComponent } from './app.component';
import { CarComponent} from './cars/car.component';
import { WheelsComponent} from './cars/wheels.component';
import { HomeComponent} from './home.component';
import { routing } from './app.routing';
import { CarService } from './cars/car.service';
#NgModule({
imports: [ BrowserModule, FormsModule, routing ],
declarations: [ AppComponent, CarComponent, WheelsComponent, HomeComponent ],
providers: [ CarService ], // <-------- SEE HERE
bootstrap: [ AppComponent ]
})
export class AppModule { }
CLICK HERE TO SEE THE DEMO

Lazy loaded module create multiples instance of the parent service each time is loaded

Every time I navigate from MainComponent to TestListComponent the TestListComponent constructor is triggered and a new instance of the ObservableServiceis created. When I click the link the console show the duplicated messages. Maybe is an angular issue, any help?
main.module.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import {MainRoutingModule} from "./main-routing.module";
import {MainComponent} from './main.component';
import {ObservableService} from "../../core/services/observable.service";
#NgModule({
imports: [
BrowserModule,
MainRoutingModule,
],
declarations: [MainComponent],
providers: [ObservableService],
bootstrap: [
MainComponent
]
})
export class MainModule { }
main.routing.module.ts
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
export const routes: Routes = [
{ path: 'tests', loadChildren: 'angular/app/modules/test-list/test-list.module#TestListModule'},
{ path: '**', redirectTo: '' }
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class MainRoutingModule {}
observable.service.ts
import { Injectable } from '#angular/core';
import {Subject} from "rxjs/Rx";
import 'rxjs/add/operator/map'
#Injectable()
export class ObservableService {
// Observable string sources
private changeLanguageStatus = new Subject<Object>();
// Observable string streams
changeLanguageStatus$ = this.changeLanguageStatus.asObservable();
constructor(){}
/**
* Change language event
* #param params
*/
changeLanguageEvent(params: Object){
this.changeLanguageStatus.next(params);
}
}
test-list.module.ts
import { NgModule } from '#angular/core';
import {TestListComponent} from "./test-list.component";
#NgModule({
declarations: [
TestListComponent
]
})
export class TestListModule {}
test-list.component.ts
import {Component} from '#angular/core';
import 'rxjs/Rx';
import {ObservableService} from "../../core/services/observable.service";
#Component({
moduleId: module.id,
selector: 'st-test-list',
templateUrl: 'test-list.component.html'
})
export class TestListComponent {
constructor(private observableService:ObservableService) {
observableService.changeLanguageStatus$.subscribe(
data => {
console.log('Test', data);
});
}
}
main.component.ts
import {Component, ViewChild} from '#angular/core';
import 'rxjs/Rx';
import {ObservableService} from "../../core/services/observable.service";
#Component({
moduleId: module.id,
selector: 'st-main',
templateUrl: 'main.component.html'
})
export class MainComponent {
constructor(private observableService:ObservableService) {}
changeLanguage(lang){
this.observableService.changeLanguageEvent({type: lang});
}
}
main.component.html
<!--Dynamic content-->
<router-outlet></router-outlet>
It should be expected behavior that when you navigate to a component via routing it is created and when you navigate back it is destroyed. As far as I know you are experiencing this issue because you are creating what is called an Infinite Observable i.e. you are subscribing to it and waiting for a stream of events, in your case changing language. Because you never unsubscribe from your Observable, the function subscribed to it is kept alive for each new instance of your component. Therefore, rxjs won't handle disposing of your subscription and you will have to do it yourself.
First off I'd suggest you read about Lifecycle hooks. Check out the OnInit and OnDestroy lifecycle hooks.
Use ngOnInit to subscribe to your Observable and use ngOnDestroy to unsubscribe from it as such:
import { Component, OnInit, OnDestroy } from '#angular/core';
import { Subscription } from 'rxjs/Subscription';
#Component({ .... })
export class TestListComponent implements OnInit, OnDestroy
{
private _languageSubscription : Subscription;
ngOnInit(): void
{
this._languageSubscription = observableService.changeLanguageStatus$.subscribe(
data => {
console.log('Test', data);
});
}
ngOnDestroy() : void
{
this._languageSubscription.unsubscribe();
}
}
I hope this will solve your problem.

HTTP service not working

This is my HttpService.ts
import { Injectable } from "#angular/core";
import { Http, Response } from "#angular/http";
import 'rxjs/add/operator/map';
#Injectable()
export class HttpService {
constructor (private http: Http) {}
getData() {
return this.http.get('http://blog_api.org/v1/posts')
.map((response: Response) => response.json());
}
}
This is my app.component.ts
import { Component } from '#angular/core';
import { HttpService } from '../app/services/HttpService'
#Component({
selector: 'my-app',
template: `Hello`,
})
export class AppComponent {
constructor (private httpService: HttpService) {};
ngOnInit() {
this.httpService.getData()
.subscribe(
data => console.log(data)
)
}
}
When I running app, I get error:
EXCEPTION: No provider for HttpService!
In your AppModule you should be doing:
import {HttpService} from "...";
import {HttpModule} from "#angular/http";
#NgModule({
bootstrap: [...],
imports: [HttpModule],
declarations: [...],
entryComponents: [...],
providers: [HttpService]
})
export default class AppModule{}
You must provide the HttpService in the model that loads the app.component.ts.
In your case, as you are using app.component.ts, provide the http in app.module.ts. Something like:
import { HttpService } from '../app/services/HttpService'
#NgModule({
...
providers: [
...
HttpService,
]
})
export class AppModule { }
Add
providers: [HttpService]
in #Component block

Categories

Resources