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

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)

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 { }

StaticInjectorError(AppModule)[AppComponent -> DataService]

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]
})

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 :-)

Get or fetch API data using Angular (v5) with services and interface?

I am working on Angular with v 5 app. I am doing API fetching and using https://angular.io/guide/http document. But I am unable to see anything in my view.
How can I fix this problem with document provided data?
My folder structure:
https://imgur.com/A03KtDy
There isn't any bug in terminal:
https://imgur.com/a/AEKxv
No issues in console:
https://imgur.com/JaPTvXZ
File: app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { HttpClientModule } from '#angular/common/http';
import { AppComponent } from './app.component';
import { NavbarComponent } from './components/navbar/navbar.component';
import { HomeComponent } from './components/home/home.component';
import { DashboardComponent } from './components/dashboard/dashboard.component';
import { ConfigService } from './services/config.service';
const appRoutes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'dashboard', component: DashboardComponent },
];
#NgModule({
declarations: [
AppComponent,
NavbarComponent,
HomeComponent,
DashboardComponent
],
imports: [
BrowserModule,
HttpClientModule,
RouterModule.forRoot(
appRoutes,
{ enableTracing: true } // <-- debugging purposes only
)
// other imports here
],
providers: [ConfigService],
bootstrap: [AppComponent]
})
export class AppModule { }
file: config.service.ts
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Config } from './config';
import { Observable } from 'rxjs/Observable';
#Injectable()
export class ConfigService {
constructor(private http: HttpClient) { }
configUrl : 'http://localhost:3000/api/get';
getConfig() {
return this.http.get<Config>(this.configUrl)
}
}
file: dashboard.component.ts
import { Component, OnInit } from '#angular/core';
import { ConfigService } from '../../services/config.service';
import { Config } from '../../services/config';
#Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
constructor(private configService : ConfigService) { }
ngOnInit() { }
config: Config;
showConfig() {
this.configService.getConfig()
// clone the data object, using its known Config shape
.subscribe(data => this.config = { ...data });
}
}
file: dashboard.component.html
<ul class="list-group" *ngFor="let config of configs">
<li class="list-group-item list-group-item-dark">{{config.name}}</li>
</ul>
file: config.ts
export interface Config {
name : string
}
I don't see in your code, that you call showConfig() method.
Maybe you forget to add call to ngOnInit() method?
ngOnInit() {
this.showConfig();
}

Resources