Service not found in NativeScript Angular - javascript

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';

Related

Angular9 'No provided for ActivatedRoute'

I'm beginner in Angular 9. I'm following an online video tutorial to excercise on angular, but my code (same of the tutorial) had a problem and I don't know of to figure out.
Actually, tutorial put routing stuffs all inside app.module.ts, but I use app-routing.module.ts to separate concerns.
When I launch 'ng serve --open', page still blank with the following error:
core.js:6185 ERROR NullInjectorError: R3InjectorError(AppModule)[ActivatedRoute -> ActivatedRoute -> ActivatedRoute]:
NullInjectorError: No provider for ActivatedRoute!
at NullInjector.get (http://localhost:4200/vendor.js:16926:27)
at R3Injector.get (http://localhost:4200/vendor.js:30642:33)
at R3Injector.get (http://localhost:4200/vendor.js:30642:33)
at R3Injector.get (http://localhost:4200/vendor.js:30642:33)
at NgModuleRef$1.get (http://localhost:4200/vendor.js:47971:33)
at Object.get (http://localhost:4200/vendor.js:45804:35)
at getOrCreateInjectable (http://localhost:4200/vendor.js:20704:39)
at Module.ɵɵdirectiveInject (http://localhost:4200/vendor.js:34541:12)
at NodeInjectorFactory.BookComponent_Factory [as factory] (http://localhost:4200/main.js:733:153)
at getNodeInjectable (http://localhost:4200/vendor.js:20849:44)
Actually I had this problem since I use providers. Is it hard to understand, because of console doesn't give any class line code. However I'm trying to describe here useful classes that should use it by following, if more classes needs, I will do that:
--app.module.ts--
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BookComponent } from './components/book/book.component';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { BooklistComponent } from './components/booklist/booklist.component';
import { BookEditComponent } from './components/book-edit/book-edit.component';
import { TreeComponent } from './components/tree/tree.component';
import { NgInitDirective } from './directive/ng-init/ng-init.directive';
// for angular firebase #https://github.com/angular/angularfire/blob/master/docs/install-and-setup.md
import { AngularFireModule } from '#angular/fire';
import { AngularFirestore } from '#angular/fire/firestore';
import { environment } from '../environments/environment';
// import our service (that uses firebase)
import { CartService } from './services/cart/cart.service'
import { HttpModule } from '#angular/http';
#NgModule({
declarations: [
AppComponent,
BookComponent,
BooklistComponent,
BookEditComponent,
TreeComponent,
NgInitDirective
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
ReactiveFormsModule,
AngularFireModule.initializeApp(environment.firebase), // have a look in firebase.ts
AngularFireModule,
HttpModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
--app-routing.module.ts--
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { BookComponent } from './components/book/book.component';
import { BookEditComponent } from './components/book-edit/book-edit.component';
import { BooklistComponent } from './components/booklist/booklist.component';
const routes: Routes = [
{ path: 'books/:title', component: BookComponent},
{ path: 'books/:title/edit', component: BookEditComponent},
{ path: 'books', component: BooklistComponent},
{
path: '',
redirectTo: 'books/',
pathMatch: 'full'
}
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
--book.component.ts--
import { Component, OnInit, Input, Output, EventEmitter } from '#angular/core';
import { BookModel } from '../../models/book/book.model';
import { CurrencyPipe } from '#angular/common';
import { ActivatedRoute } from '#Angular/router'
import { CartService } from '../../services/cart/cart.service';
#Component({
selector: 'book',
templateUrl: './book.component.html',
styleUrls: ['./book.component.css']
})
export class BookComponent implements OnInit {
#Input() book: BookModel;
#Output() addToCart: EventEmitter<BookModel> = new EventEmitter();
constructor(private route: ActivatedRoute, private cs: CartService) {
route.params.subscribe(res => {
this.book = BookModel.find(res['title']);
});
}
ngOnInit(): void {
}
sendToCart() {
this.addToCart.emit(this.book);
// the following method is added in cart.service.ts
this.cs.add(this.book);
}
// methods
votesCounter() {
return this.book.upvotes;
}
upvote() {
return this.book.upvotes++;
}
}
As I use app-routing.module.ts, there is a quite difference in app.module of tutorial (that puts also routing stuffs inside it):
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { RouterModule, Routes } from '#angular/router';
import { AngularFireModule } from 'angularfire2';
import { AngularFirestore } from 'angularfire2/firestore';
import { environment } from '../environments/environment';
import { AppComponent } from './app.component';
import { BookComponent } from './components/book/book.component';
import { BookListComponent } from './components/book-list/book-list.component';
import { BookEditComponent } from './components/book-edit/book-edit.component';
import { TreeComponent } from './components/tree/tree.component';
import { NgInitDirective } from './directive/ng-init/ng-init.directive';
import { CartService } from './services/cart/cart.service';
const bookRoutes: Routes = [
{ path: 'books/:title', component: BookComponent },
{ path: 'books/:title/edit', component: BookEditComponent },
{ path: 'books', component: BookListComponent },
{
path: '',
redirectTo: 'books/',
pathMatch: 'full'
}
]
#NgModule({
declarations: [
AppComponent,
BookComponent,
BookListComponent,
BookEditComponent,
TreeComponent,
NgInitDirective
],
imports: [
RouterModule.forRoot(bookRoutes),
BrowserModule,
FormsModule,
ReactiveFormsModule,
AngularFireModule.initializeApp(environment.firebase),
AngularFireModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
I tryed with solutions given from similar questions, but it doesn't work.
You have a typing error,
change #Angular/router with #angular/router in book.component.ts

angular2 websocket error: Cannot read property 'subscribe' of undefined

I am using angular-cli.
I am trying to implement this example:
https://www.npmjs.com/package/angular2-websocket-service
I have created my service, and I want to use it directly in AppComponent.
This is what I have:
app/app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
import { WebSocketService } from 'angular2-websocket-service'
import { MyWebsocketService } from './websocket/mywebsocket.service';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [
WebSocketService,
MyWebsocketService
],
bootstrap: [AppComponent]
})
export class AppModule { }
app/app.component.ts
import { Component, OnInit } from '#angular/core';
import {MyWebsocketService} from './websocket/mywebsocket.service'
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'title';
constructor(private mywebsocket: MyWebsocketService) { }
ngOnInit() {
this.mywebsocket.connect();
}
}
app/websocket/mywebsocket.service.ts
import { Injectable } from '#angular/core';
import { WebSocketService } from 'angular2-websocket-service'
import { Observable } from 'rxjs/Observable'
import { Subscription } from 'rxjs/Subscription';
import 'rxjs/add/operator/share'
#Injectable()
export class MyWebsocketService {
private q: Observable<any>
private w: Observable<any>
constructor(private socketFactory: WebSocketService) { }
public connect() {
this.q = new Observable<any>()
this.w = this.socketFactory.connect('ws://localhost:8080/myapp/cswebsocket', this.q).share()
this.w.subscribe()
}
}
And here is what I get:
> core.js:1350 ERROR TypeError: Cannot read property 'subscribe' of
> undefined
Why would this.w be undefined? How can I solve this?

ERROR while adding custom module to parent app module in angular

I am trying to add new module to make my angular application more modular and for lazy loading.
app.module
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { HttpModule,BrowserXhr } from "#angular/http";
import { LabService } from './lab/lab.service';
import { FormsModule } from '#angular/forms';
import { AppComponent } from './app.component';
import { OphistoryModule } from './Ophistory/ophistory.Module' //after adding this module ERROR is thrown
#NgModule({
imports:[
BrowserModule,
HttpModule,
FormsModule,
RouterModule.forRoot([
{path: 'labDetails/:labName',component:LabDetailsComponent},
{path:'showRoboLog/:labName',component:RoboLogComponent},
{path:'',component:LabComponent}
]),
OphistoryModule
],
declarations: [
AppComponent
],
bootstrap:[ AppComponent ]
})
export class AppModule {}
app.component
import { Component } from '#angular/core';
import { Http } from '#angular/http';
import { LabComponent } from './lab/lab.component';
import { LabService } from './lab/lab.service';
#Component({
selector: 'my-app',
template: `
<router-outlet></router-outlet>
`,
providers: [LabService]
})
export class AppComponent {
constructor() {
}
pageTitle: string = 'ABC';
}
The problem I am facing after adding the module OphistoryModule is an error message saying
my-app' is not a known element:
But when I give the same name to the selector of my newly added module it is working fine.
Here are the custom module and component
ophistory.module
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser'
import { OphistoryComponent } from './ophistory.component'
import {CommonModule} from '#angular/common'
#NgModule({
imports: [RouterModule.forChild([
{path: 'test',component:OphistoryComponent}
]),CommonModule],
declarations:[OphistoryComponent]
})
export class OphistoryModule {}
ophistory.component
import { Component } from '#angular/core'
import { LabService } from '../lab/lab.service'
#Component({
selector:'my-ap',
templateUrl:'./ophistory.component.html'
})
export class OphistoryComponent {
constructor (private _service:LabService){}
}
Can anyone confirm if it is a bug in angular 2 or any other solution you have?

component can't find provider from lazy-loaded module

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.

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