StaticInjectorError(AppModule)[AppComponent -> DataService] - node.js

I have been following tutorials on setting up a mean stack, yet when running my code on localhost I get a blank screen with the error 'StaticInjectorError(AppModule)[DataService -> Http]:'. I've spent two days trying to figure out this bug, and couldn't find anything.
As for details on the tools I'm using, Angular 8.3.17, node v12
data.service.ts
import { Injectable } from '#angular/core';
import { Http, Headers, RequestOptions } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class DataService {
result:any;
constructor(private _http: Http) { }
getAccounts() {
return this._http.get("/api/accounts")
.map(result => this.result = result.json().data);
}
}
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 the Http Module and our Data Service
import { HttpModule } from '#angular/http';
import { DataService } from './data.service';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts
import { Component } from '#angular/core';
// Import the DataService
import { DataService } from './data.service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
// Define a users property to hold our user data
accounts: Array<any>;
// Create an instance of the DataService through dependency injection
constructor(private _dataService: DataService) {
// Access the Data Service's getUsers() method we defined
this._dataService.getAccounts()
.subscribe(res => this.accounts = res);
}
}

You need to add DataService in providers part of app.module.ts file like this
providers: [DataService],

I found the problem, I had to add dataService to my providers array, and HttpModule to imports.
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpModule,
AppRoutingModule
],
providers: [DataService],
bootstrap: [AppComponent]
})

Related

Angular + Node: Executing a GET call to the server, angular adds it's own address

Angular version: Angular: 12.2.9
I'm learning Node + Angular. I have an endpoint that works fine (tested with postman), but when I want to call it from the Angular project, the request is made to http://localhost:4200/localhost:8010/api/photos when it should be to http://localhost:8010/api/photos
This is the service:
import { Injectable } from '#angular/core';
import { GLOBAL } from './global';
import { Http } from '#angular/http';
#Injectable({
providedIn: 'root'
})
export class FotografiasService {
private url:string;
constructor(private _http:Http) {
this.url=GLOBAL.url;
}
getFotografias(){
return this._http.get(this.url + 'fotografias')
.toPromise().then(res=>res.json());
}
}
This is the component
import { Component, OnInit } from '#angular/core';
import { FotografiasService } from 'src/app/services/fotografias.service';
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
public fotografias:any[] | undefined;
constructor(private _serviceFotografias:FotografiasService) { }
ngOnInit(): void {
this.getFotografias();
}
getFotografias(){
this._serviceFotografias.getFotografias()
.then(response=>{
this.fotografias=response.fotografias;
})
.catch(error=>{
console.log(error);
})
}
}
app.module
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { MatIconModule } from '#angular/material/icon';
import { HttpModule } from '#angular/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './components/home/home.component';
import { AppRouting } from './routes/routing';
#NgModule({
declarations: [
AppComponent,
HomeComponent
],
imports: [
BrowserModule,
AppRoutingModule,
MatIconModule,
AppRouting,
HttpModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

How to fix 'Uncaught Error: Can't resolve all parameters for AuthService: (?).'

this error occur when application is started.
The terminal is not showing any error but in the browser console.
The last action was i import JwtHelperService from '#auth0/angular-jwt'
The project is in Nodejs, express 4.16.4 and angular 7.2.0
I have included some code
please help me to find the error
thank you in advance
auth.service.ts
import { Injectable } from "#angular/core";
import { Observable } from "rxjs";
import "rxjs/Rx";
import { JwtHelperService } from "#auth0/angular-jwt";
import { map } from "rxjs/operators";
import "core-js/es7/reflect";
import { HttpClient } from "#angular/common/http";
const jwt = new JwtHelperService();
export class AuthService {
#Injectable()
private decodedToken;
constructor(private http: HttpClient) {}
public register(userData: any): Observable<any> {
return this.http.post("/api/v1/users/register", userData);
}
public login(userData: any): Observable<any> {
return this.http.post("/api/v1/users/auth", userData).map(token => {
//debugger;
return this.saveToken(token);
});
}
private saveToken(token): string {
//debugger;
this.decodedToken = jwt.decodeToken(token);
localStorage.setItem("bwm_auth", token.token);
localStorage.setItem("bwm_meta", JSON.stringify(this.decodedToken));
return token;
}
}
app.module.ts
import { NgModule } from "#angular/core";
import { CommonModule } from "#angular/common";
import { FormsModule, ReactiveFormsModule } from "#angular/forms";
import { Routes, RouterModule } from "#angular/router";
import { LoginComponent } from "./login/login.component";
import { RegisterComponent } from "./register/register.component";
import { AuthService } from "./shared/auth.service";
const routes: Routes = [
{ path: "login", component: LoginComponent },
{ path: "register", component: RegisterComponent }
];
#NgModule({
declarations: [LoginComponent, RegisterComponent],
imports: [
RouterModule.forChild(routes),
FormsModule,
CommonModule,
ReactiveFormsModule
],
exports: [],
providers: [AuthService]
})
export class AuthModule {}
error on browser
compiler.js:2430 Uncaught Error: Can't resolve all parameters for AuthService: (?).
at syntaxError (compiler.js:2430)
at CompileMetadataResolver.push../node_modules/#angular/compiler/fesm5/compiler.js.CompileMetadataResolver._getDependenciesMetadata (compiler.js:18984)
at CompileMetadataResolver.push../node_modules/#angular/compiler/fesm5/compiler.js.CompileMetadataResolver._getTypeMetadata (compiler.js:18877)
at CompileMetadataResolver.push../node_modules/#angular/compiler/fesm5/compiler.js.CompileMetadataResolver._getInjectableTypeMetadata (compiler.js:19099)
at CompileMetadataResolver.push../node_modules/#angular/compiler/fesm5/compiler.js.CompileMetadataResolver.getProviderMetadata (compiler.js:19108)
at compiler.js:19046
at Array.forEach (<anonymous>)
at CompileMetadataResolver.push../node_modules/#angular/compiler/fesm5/compiler.js.CompileMetadataResolver._getProvidersMetadata (compiler.js:19006)
at CompileMetadataResolver.push../node_modules/#angular/compiler/fesm5/compiler.js.CompileMetadataResolver.getNgModuleMetadata (compiler.js:18725)
at CompileMetadataResolver.push../node_modules/#angular/compiler/fesm5/compiler.js.CompileMetadataResolver.getNgModuleSummary (compiler.js:18555)
image of error in browser
#Injectable() should be placed before the class definition
#Injectable()
export class AuthService {
}
You should first add #Injectable to your AuthService
But this error indicates that the DI cannot resolve the requested parameter asked by the AuthService (HttpClient).
To resolve this issue, you need to include the HttpClient module in your AppModule as this code snippet shows
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { HttpClientModule } from '#angular/common/http';
#NgModule({
imports: [
BrowserModule,
// import HttpClientModule after BrowserModule.
HttpClientModule,
],
declarations: [
AppComponent,
],
bootstrap: [ AppComponent ]
})
export class AppModule {}
You can see their full documentation here HttpModule

Loading a different component.html file from a component.ts file?

I'm new to angular and I was wondering how I could load a different home.component.html file from a method that's inside books.component.ts.
This is my books.component.ts file.
import { Component, OnInit } from '#angular/core';
import {BooksService} from '../books.service';
import {NgForm} from '#angular/forms';
import { Router } from '#angular/router';
#Component({
selector: 'app-books',
templateUrl: './books.component.html',
styleUrls: ['./books.component.css']
})
export class BooksComponent {
constructor(private httpService: BooksService, private router:Router) {
}
status : any;
onSubmit(f: NgForm) {
console.log("AM I HERE AT LEAST");
this.httpService.checkLoginCred(f.value).subscribe(
data => {
// console.log(Object.values(data)[0]);
this.status = Object.values(data)[0];
if(this.status === "Successful"){
var path = "../home/home.component.html";
// console.log($location.path());
//console.log(this.router);
this.router.navigate(['/home']);
console.log("GREAT!");
}
return true;
}
);
}
}
my app.module.ts looks like so:
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { HttpClientModule } from '#angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BooksComponent } from './books/books.component';
import { HomeComponent } from './home/home.component';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { RouterModule, Routes } from '#angular/router';
#NgModule({
declarations: [
AppComponent,
BooksComponent,
HomeComponent,
],
imports: [
RouterModule.forRoot([
{
path: 'home',
component: HomeComponent
}
]),
BrowserModule,
HttpClientModule,
AppRoutingModule,
FormsModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
my books.component.ts and books.component.html files are in my books directory.
my home.component.ts and home.component.html files are in my home directory
I've attached a screenshot of how my directory structure looks like.
So far I'm trying to use this.router.navigate but I'm not having much luck with that.
Any help would be greatly appreciated!
EDIT
My home.component.ts file looks like so:
import { Component } from '#angular/core';
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent {
constructor() { }
}
As we discussed - here is the solution - hope it works
Add only <router-outlet></router-outlet> on app.compoment.html and using routing try to render the components
Your route should read as
RouterModule.forRoot([
{
path: 'home',
component: HomeComponent
},
{
path: 'book',
component: BookComponent
},
{
path: '',
redirectTo: 'book'
pathMatch: 'full'
}
])
Thus on the initial load your path will match empty and redirect to BookComponent and inside the book component when you navigate it will load the HomeComponent inside the AppComponent html
Hope this might solve your problem - happy coding :-)

Can't resolve all parameters for LoginComponent: ([object Object], ?, ?) in ANGULAR

i am building a imple login authentication using passport.js and i am getting this error this error has became i headache for me i am getting no error on my Gitcmd and node server but when i am trying to go to my browser i am getting this error
This is me user.service.ts
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
#Injectable()
export class UserService {
constructor(private http:HttpClient) { }
register(body:any){
return this.http.post('http://127.0.0.1:3000/users/register',body,{
observe:'body',
headers:new HttpHeaders().append('Content-Type','application/json')
})
}
login(body:any){
return this.http.post('http://127.0.0.1:3000/users/login',body,{
observe:'body',
withCredentials:true,
headers:new HttpHeaders().append('Content-Type','application/json')
})
}
}
This is my login.component.ts
import { Component, OnInit } from '#angular/core';
import {Router} from '#angular/router';
import { FormGroup, FormControl, Validators } from '#angular/forms';
import {UserService} from '../user.service';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
loginForm:FormGroup=new FormGroup({
email:new FormControl(null,[Validators.email,Validators.required]),
password:new FormControl(null,Validators.required)
})
constructor(private router:Router,private user,UserService) { }
ngOnInit() {
}
//This is doing nothing just on Login Component when the
//User click Register button it takes it to Register Page
moveToRegister(){
this.router.navigate(['/register']);
}
//Now we have to Bind this function in our Html file
login(){
if(!this.loginForm.valid){
console.log('Invalid');
return;
}
// console.log(JSON.stringify(this.loginForm.value));
this.user.login(JSON.stringify(this.loginForm.value))
.subscribe(
data=>{console.log(data);this.router.navigate(['/user']);},
error=>console.error(error)
)
}
}
this is mine 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 { LoginComponent } from './login/login.component';
import { RegisterComponent } from './register/register.component';
import { UserhomeComponent } from './userhome/userhome.component';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import {UserService} from './user.service';
import { HttpClientModule } from '#angular/common/http';
#NgModule({
declarations: [
AppComponent,
LoginComponent,
RegisterComponent,
UserhomeComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
ReactiveFormsModule,
HttpClientModule
],
providers: [UserService],
bootstrap: [AppComponent]
})
export class AppModule { }
You shouldn't have a comma here:
constructor(private router:Router,private user,UserService)
^
It should be:
constructor(private router: Router, private user: UserService)

How to use js function from imported npm package in angular 4

I'm using angular 4, here is the problem I have proposal-list component, and I would like to use accounting-js from npmjs for accounting-js and link documentation how to use the function, I installed using
npm install accounting-js
here is my proposal-list.component.ts
import { Component, OnInit } from '#angular/core';
import { formatNumber } from 'accounting-js/lib/formatNumber.js';
#Component({
selector: 'app-proposal-list',
templateUrl: './proposal-list.component.html',
styleUrls: ['./proposal-list.component.css']
})
export class ProposalListComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
my question how I can use the function inside formatNumber.js?
I tried to use in proposal-list.component.html
total money = {{formatNumber(1000500.65)}}
but it's not showed up, but no error message.
addional info for problem
here is my app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AlertModule } from 'ngx-bootstrap';
import { BsDropdownModule } from 'ngx-bootstrap';
import { FormsModule } from '#angular/forms';
import { AppComponent } from './app.component';
import { HomepageComponent } from './homepage/homepage.component';
import { AppRoutingModule } from './app-routing.module';
import { DocumentsComponent } from './documents/documents.component';
import { ProposalListComponent } from './proposal/proposal-list/proposal-list.component';
import { ProposalShowComponent } from './proposal/proposal-show/proposal-show.component';
import { ProposalNewComponent } from './proposal/proposal-new/proposal-new.component';
#NgModule({
declarations: [
AppComponent,
HomepageComponent,
DocumentsComponent,
ProposalListComponent,
ProposalShowComponent,
ProposalNewComponent
],
imports: [
AlertModule.forRoot(),
BsDropdownModule.forRoot(),
BrowserModule,
AppRoutingModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
you should be doing it in your ts file and if you want to do it in your html then you have to define a function in your ts. Try this.
import { Component, OnInit } from '#angular/core';
import { formatNumber } from 'accounting-js/lib/formatNumber.js';
#Component({
selector: 'app-proposal-list',
templateUrl: './proposal-list.component.html',
styleUrls: ['./proposal-list.component.css']
})
export class ProposalListComponent implements OnInit {
private money: number ;
constructor() { }
ngOnInit() {
this.money = formatNumber(1000500.65)
}
}
and in your html
total money = {{money}}
but if you want to use it on the fly, you can create a custom pipe using FormatNumber function
import { Pipe, PipeTransform } from '#angular/core';
import { formatNumber } from 'accounting-js/lib/formatNumber.js';
#Pipe({name: 'formatNumber'})
export class FormatNumberPipe implements PipeTransform {
transform(money:number): number {
return formatNumber(money)
}
}
and can use it like
total money = 1000500.65 | formatNumber
Update
You must include your pipe in the declarations array of the AppModule.
app.module.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import { AppComponent } from './app.component';
import { FormatNumberPipe} from './pipe.component';// whatever the name of your pipe component
#NgModule({
imports: [
BrowserModule,
FormsModule,
HttpModule
],
declarations: [
AppComponent,
FormatNumberPipe// **<-- this guy**
]
......
if the import is a problem then you need to think about these below stuffs.
wat is the export type of the function in side your js file like UMD, AMD, es2015, etc
then you need to understand which types of module is imported in which way in typescript.
once you imported the module/function you can then call them from your typescript
like you can import open function import * as services from 'thisService'
But if that function is inside a module, you need to import it from the module like imort { service} from 'thisServiceModule'.
Hope it helps

Resources