React + Redux + oidc - redux

I have problems when I try add oidc provider in index.tsx
I use React with Redux Toolkit.
I have this code in other project. It works fine there.
I try change dependencies from my work project, but it didn't do anything.
Projects differ only in dependency versions.
index.tsx
root.render(
<Provider store={store}>
<OidcProvider store={store} userManager={userManager}>
<BrowserRouter>
<App />
</BrowserRouter>
</OidcProvider>
</Provider>,
)
OidcProvider -> error ->
TS2769: No overload matches this call.   Overload 1 of 2, '(props: OidcProviderProps<CombinedState<{ oidc: UserState; notify: INotifys; }>> | Readonly<OidcProviderProps<CombinedState<{ oidc: UserState; notify: INotifys; }>>>): OidcProvider<...>', gave the following error.     Type '{ children: Element; store: ToolkitStore<CombinedState<{ oidc: UserState; notify: INotifys; }>, AnyAction | Action<User | Error>, [...]>; userManager: UserManager; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<OidcProvider<CombinedState<{ oidc: UserState; notify: INotifys; }>>> & Readonly<...>'.       Property 'children' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<OidcProvider<CombinedState<{ oidc: UserState; notify: INotifys; }>>> & Readonly<...>'.   Overload 2 of 2, '(props: OidcProviderProps<CombinedState<{ oidc: UserState; notify: INotifys; }>>, context: any): OidcProvider<CombinedState<{ oidc: UserState; notify: INotifys; }>>', gave the following error.     Type '{ children: Element; store: ToolkitStore<CombinedState<{ oidc: UserState; notify: INotifys; }>, AnyAction | Action<User | Error>, [...]>; userManager: UserManager; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<OidcProvider<CombinedState<{ oidc: UserState; notify: INotifys; }>>> & Readonly<...>'.       Property 'children' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<OidcProvider<CombinedState<{ oidc: UserState; notify: INotifys; }>>> & Readonly<...>'.
store.ts
import {configureStore} from "#reduxjs/toolkit"
import {loadUser} from "redux-oidc"
import {rootReducer} from "./rootReducer"
import {userManager} from "../config/userManager"
const loadUserDefault = () => {
userManager
.clearStaleState()
.then(() => loadUser(store, userManager))
.catch((err) => console.error(err))
}
export function customConfigureStore() {
const store = configureStore({
reducer: rootReducer,
})
loadUserDefault()
return store
}
export const store = customConfigureStore()
export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch
userManager.ts
import {
UserManager,
UserManagerSettings,
WebStorageStateStore,
} from "oidc-client"
import {pathsList} from "./pathList"
const uri = `${window.location.protocol}//${window.location.hostname}${
window.location.port ? `:${window.location.port}` : ""
}`
const userManagerConfig: UserManagerSettings = {
/**
other my code
**/
loadUserInfo: true,
userStore: new WebStorageStateStore({store: localStorage}),
includeIdTokenInSilentRenew: true,
monitorSession: false,
}
export const userManager = new UserManager(userManagerConfig)
packeg.json
***
"#reduxjs/toolkit": "^1.9.2",
"antd": "^5.2.1",
"axios": "^1.3.2",
"oidc-client": "^1.11.5",
"postcss": "^8.4.21",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-hook-form": "^7.43.1",
"react-redux": "^8.0.5",
"react-router-dom": "^6.8.1",
"react-scripts": "5.0.1",
"redux": "^4.2.1",
"redux-oidc": "^4.0.0-beta1",
"redux-thunk": "^2.4.2"
***
What could be the problem?

Related

getServerSession() returning null in api route when using NextJs and Next-Auth

I'm new to NextJS and Next-Auth.
I'm trying to write a secure api route that is only available if a user is logged in.
I sucessfully accessing the session on the client side using useSession() but when I try to implement the logic in an api route the session always returns null.
I have tried to copy the simpliest example from the docs. Am I missing something?
Here is my route in src/pages/api/users/getUser.ts:
import { getServerSession } from 'next-auth/next'
import { authOptions } from '../auth/[...nextauth]'
import { NextApiRequest, NextApiResponse } from 'next'
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const session = await getServerSession(req, res, authOptions)
console.log('session', session)
if (session) {
res.send({ content: 'SUCCESS' })
} else {
res.send({ error: 'ERROR' })
}
}
Here is my authOptions in src/pages/api/auth/[...nextauth].ts
import NextAuth from 'next-auth'
import GithubProvider from 'next-auth/providers/github'
import { PrismaAdapter } from '#next-auth/prisma-adapter'
import prisma from '../../../../prisma/db/prismadb'
export const authOptions = {
adapter: PrismaAdapter(prisma),
providers: [
GithubProvider({
clientId: process.env.GITHUB_ID || '',
clientSecret: process.env.GITHUB_SECRET || '',
}),
],
pages: {
signIn: '/',
signOut: '/',
},
}
export default NextAuth(authOptions)
Here are my dependencies:
"dependencies": {
"#next-auth/prisma-adapter": "^1.0.5",
"#next/font": "13.1.6",
"#prisma/client": "^4.10.1",
"#types/node": "18.11.19",
"#types/react": "18.0.27",
"#types/react-dom": "18.0.10",
"axios": "^1.3.2",
"dotenv-cli": "^7.0.0",
"eslint": "8.33.0",
"eslint-config-next": "13.1.6",
"next": "13.1.6",
"next-auth": "^4.19.2",
"prisma": "^4.9.0",
"react": "18.2.0",
"react-dom": "18.2.0",
"styled-components": "^5.3.6",
"typescript": "4.9.5"
},
"devDependencies": {
"#types/styled-components": "^5.1.26"
}
In my case, when NEXTAUTH_URL is 127.0.0.1 and API is requested to localhost, the session is null.
So, I solved the problem by matching the NEXTAUTH_URL with the request URL.

Uncaught SyntaxError: The requested module '/node_modules/.vite/deps/vue-router.js' does not provide an export named 'default'

I'm having some issues with installing vue-router with laravel. Laravel 9, Vue.js 3
routes.js
import AllBooks from './components/AllBooks.vue';
import CreateBook from './components/CreateBook.vue';
import EditBook from './components/EditBook.vue';
export const routes = [
{
name: 'home',
path: '/',
component: AllBooks
},
{
name: 'create',
path: '/create',
component: CreateBook
},
{
name: 'edit',
path: '/edit/:id',
component: EditBook
}
];
Here's my config:-
resources/js/app.js
import './bootstrap';
import { createApp } from 'vue';
const app = createApp({})
import App from './App.vue';
import VueAxios from 'vue-axios';
import VueRouter from 'vue-router'; // problem!!
import axios from 'axios';
import { routes } from './routes';
const router = VueRouter.createRouter({
// 4. Provide the history implementation to use. We are using the hash history for simplicity here.
history: VueRouter.createWebHashHistory(),
routes,
})
// Make sure to _use_ the router instance to make the
// whole app router-aware.
app.use(router)
app.mount('#app')
package.json
"devDependencies": {
"#popperjs/core": "^2.11.6",
"#vitejs/plugin-vue": "^3.0.1",
"axios": "^1.1.2",
"bootstrap": "^5.2.3",
"laravel-vite-plugin": "^0.7.2",
"lodash": "^4.17.19",
"postcss": "^8.1.14",
"sass": "^1.56.1",
"vite": "^4.0.0",
"vue": "^3.2.37"
},
"dependencies": {
"vue-axios": "^3.5.2",
"vue-router": "^4.1.6"
}
If you could help me with vue-router doesn't provide an export?
import VueRouter from '/node_modules/.vite/deps/vue-router.js?v=05a616f1';
In my case, look out for duplicated entries for our vue libraries. I had:-
resources/views/layouts/app.blade.php
<script src="https://unpkg.com/vue#3"></script>
<script src="https://unpkg.com/vue-router#4"></script>
AND
package.json
"dependencies": {
"vue": "^3.2.45",
"vue-router": "^4.1.6"
}
also, my config changed in:-
resources/js/app.js
import './bootstrap';
import * as Vue from 'vue';
import * as VueRouter from 'vue-router'; // alternative ways of importing
import LoginComponent from "./components/LoginComponent.vue";
import TestComponent from "./components/TestComponent.vue";
const Home = { template: '<div>Home</div>' }
const routes = [
{ path: '/', component: Home },
{ path: '/login', name: "Login", component: LoginComponent },
{ path: '/test', name: "Test", component: TestComponent },
]
const router = VueRouter.createRouter({
history: VueRouter.createWebHashHistory(),
routes,
})
const app = Vue.createApp({})
app.use(router)
app.mount('#app')
If this helps you, well keep truckin. :)

NullInjectorError: No provider for InjectionToken angularfire2.app.options! 2021

Okay I just started using angular firebase and I've been scratching my head for two days. Most of the tutorials out there are mostly for older versions of firebase
this is the error that I am receiving when I inject my authentication service to the component
Uncaught (in promise): NullInjectorError: R3InjectorError(AppModule)[LoginService -> AngularFireAuth -> InjectionToken angularfire2.app.options -> InjectionToken angularfire2.app.options -> InjectionToken angularfire2.app.options]:
NullInjectorError: No provider for InjectionToken angularfire2.app.options!
NullInjectorError: R3InjectorError(AppModule)[LoginService -> AngularFireAuth -> InjectionToken angularfire2.app.options -> InjectionToken angularfire2.app.options -> InjectionToken angularfire2.app.options]:
NullInjectorError: No provider for InjectionToken angularfire2.app.options!
the following links haven't been helpful so far
Link1 Link2 Link3
app.module.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { HttpClientModule } from '#angular/common/http';
import { LoginService } from 'src/services/login.service';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { LoginComponent } from './components/login/login.component';
import { HomeComponent } from './components/home/home.component';
import { NotFoundComponent } from './components/not-found/not-found.component';
import { environment } from '../environments/environment';
import { initializeApp,provideFirebaseApp } from '#angular/fire/app';
import { provideAuth,getAuth } from '#angular/fire/auth';
import { provideDatabase,getDatabase } from '#angular/fire/database';
import { provideFirestore,getFirestore } from '#angular/fire/firestore';
import { AngularFirestore } from '#angular/fire/compat/firestore';
#NgModule({
declarations: [
AppComponent,
LoginComponent,
HomeComponent,
NotFoundComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
provideFirebaseApp(() => initializeApp(environment.firebase)),
provideAuth(() => getAuth()),
provideDatabase(() => getDatabase()),
provideFirestore(() => getFirestore()),
FormsModule,
ReactiveFormsModule
],
providers: [LoginService],
bootstrap: [AppComponent]
})
export class AppModule { }
login.service.ts
import { Injectable } from '#angular/core';
import { AngularFireAuth } from '#angular/fire/compat/auth';
import { Router } from '#angular/router';
import { AngularFirestore } from '#angular/fire/compat/firestore';
#Injectable({
providedIn: 'root'
})
export class LoginService {
userLoggedIn: boolean;
constructor(private afAuth: AngularFireAuth, private router : Router, private afs: AngularFirestore) {
this.userLoggedIn = false;
}
loginUser(email: string, password: string): Promise<any> {
return this.afAuth.signInWithEmailAndPassword(email,password)
.then(() => {
console.log('Auth Service: loginUser: success');
this.router.navigate(['']);
})
.catch(error => {
console.log('Auth Service: login error...');
console.log('error code', error.code);
console.log('error', error);
if (error.code)
return { isValid: false, message: error.message };
else
return { isValid: false, message : "Login Error"}
});
}
}
login.component.ts
import { Component, OnInit } from '#angular/core';
import { FormControl, FormGroup, Validators } from '#angular/forms';
import { Router } from '#angular/router';
import { LoginService } from 'src/services/login.service';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
loginFormCtrl: FormGroup;
constructor(private LoginService: LoginService, private router: Router) {
this.loginFormCtrl = new FormGroup({
email: new FormControl('', Validators.required),
password: new FormControl(null, Validators.required)
})
}
ngOnInit(): void {
}
onLogin() {
if (this.loginFormCtrl.invalid)
return;
this.LoginService.loginUser(this.loginFormCtrl.value.email, this.loginFormCtrl.value.password).then((result) => {
if (result == null) {
console.log('logging in...');
this.router.navigate(['']);
}
else if (result.isValid == false) {
console.log('login error', result);
}
});
}
}
package.json
{
"name": "fire-base",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test"
},
"private": true,
"dependencies": {
"#angular/animations": "~12.2.0",
"#angular/common": "~12.2.0",
"#angular/compiler": "~12.2.0",
"#angular/core": "~12.2.0",
"#angular/fire": "^7.1.1",
"#angular/forms": "~12.2.0",
"#angular/platform-browser": "~12.2.0",
"#angular/platform-browser-dynamic": "~12.2.0",
"#angular/router": "~12.2.0",
"rxjs": "~6.6.0",
"tslib": "^2.3.0",
"zone.js": "~0.11.4",
"firebase": "^9.1.0",
"rxfire": "^6.0.0"
},
"devDependencies": {
"#angular-devkit/build-angular": "~12.2.7",
"#angular/cli": "~12.2.7",
"#angular/compiler-cli": "~12.2.0",
"#types/jasmine": "~3.8.0",
"#types/node": "^12.11.1",
"jasmine-core": "~3.8.0",
"karma": "~6.3.0",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage": "~2.0.3",
"karma-jasmine": "~4.0.0",
"karma-jasmine-html-reporter": "~1.7.0",
"typescript": "~4.3.5"
}
}
The fix is actually really simple...
in your app.module.ts
import
import { FIREBASE_OPTIONS } from '#angular/fire/compat';
and then add this to the providers
providers: [
{ provide: FIREBASE_OPTIONS, useValue: environment.firebase }
],
It seems that AngularFire is in the middle of major changes that embrace Firebase's new modular API, but the documentation hasn't quite caught up. The gist is that the you are initializing the Firebase App using the new API, but trying to use Firebase resources with the old API.
The key is to look at the import statement. Compare old and new style of initializing the app:
import {AngularFireModule} from '#angular/fire/compat';
[...]
imports: [
AngularFireModule.initializeApp(environment.firebase),
]
vs.
import {initializeApp, provideFirebaseApp} from '#angular/fire/app';
[...]
imports: [
provideFirebaseApp( () => initializeApp(environment.firebase)),
]
Notice how the old style initialization is under the "compat" namespace. If you initialize your app this way, you must also use the compat libraries to access resources. For example, from the AngularFire docs:
import {AngularFirestore, AngularFirestoreDocument} from '#angular/fire/compat/firestore';
[...]
constructor(private afs: AngularFirestore) {
this.itemDoc = afs.doc<Item>('items/1');
this.item = this.itemDoc.valueChanges();
}
However, this doesn't work with the new style app initialization. Instead you must use something like this, adapted from the Firebase docs:
import {doc, Firestore, getDoc} from '#angular/fire/firestore';
[...]
constructor(private firestore: Firestore) { }
[...]
const docRef = doc(this.firestore, "cities", "SF");
const docSnap = await getDoc(docRef);
Why does it matter? I assume, but do not know, that the instance of the app is not shared between old and new.
So, the moral of the story:
Most of the documentation on the internet uses the old API. If you want to use that API, use the "compat" version of the library.
If you want to use the modern modular API, make sure you're not using the "compat" library. And the best bet is to refer to the Firebase documentation until the AngularFire team has had a chance to catch up.
I had the same problem today and I agree: there's many versions and their documentation is disappointing.
The solution (in my case)
For my setup (angular 11 + angular/fire 6.1.5) i had to put the following in my app.module.ts file:
...
imports: [
...
AngularFireModule.initializeApp(environment.firebase),
],
...
(For me environment.firebase contains my firebase config.)
Further analysis of the problem below, you can stop reading if you don't care
The documentation for angular/fire 7 will tell you to do this:
provideFirebaseApp(() => initializeApp(environment.firebase)),
Which I'm sure works great for version 7, but angular 11 automatically installs version 6, because that's compatible.
My issue was fixed when I used both versions of initialization
AngularFireModule.initializeApp(environment.firebase),
provideFirebaseApp(() => initializeApp(environment.firebase)),
I have the same issue using auth-guard.
Fixed it by dropping the compat in the import path.
Before
import { hasCustomClaim, canActivate } from '#angular/fire/compat/auth-guard';
After
import { hasCustomClaim, canActivate } from '#angular/fire/auth-guard';
On the file App.component.ts add the following provider object:
import { FIREBASE_OPTIONS } from '#angular/fire/compat';
#NgModule({
providers: [
{ provide: FIREBASE_OPTIONS, useValue: environment.firebaseConfig }
],
})
taked from: [https://www.angularfix.com/2022/03/angular-fire-no-provider-for.html][1]
As advised by #Daniel Eisenhardt I downgraded my angular version. And it is now working ! Angular : ~11.2.4
and running ng add #angular/fire installed a compatible version of angular fire. ("^6.1.5")
This is my updated file
app.module.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './component/home/home.component';
import { LoginComponent } from './component/login/login.component';
import { NotFoundComponent } from './component/not-found/not-found.component';
import { AngularFireModule } from '#angular/fire';
import { AngularFirestoreModule } from '#angular/fire/firestore';
import { AngularFireDatabaseModule } from '#angular/fire/database';
// import { AngularFireStorageModule } from '#angular/fire/storage';
import { environment } from '../environments/environment';
#NgModule({
declarations: [
AppComponent,
HomeComponent,
LoginComponent,
NotFoundComponent
],
imports: [
BrowserModule,
AppRoutingModule,
AngularFireModule.initializeApp(environment.firebase)
AngularFirestoreModule,                              
AngularFireDatabaseModule,
FormsModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
package.json
{
"name": "evnt-mgmnt-app",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"#angular/animations": "~11.2.14",
"#angular/common": "~11.2.14",
"#angular/compiler": "~11.2.14",
"#angular/core": "~11.2.14",
"#angular/fire": "^6.1.5",
"#angular/forms": "~11.2.14",
"#angular/platform-browser": "~11.2.14",
"#angular/platform-browser-dynamic": "~11.2.14",
"#angular/router": "~11.2.14",
"rxjs": "~6.6.0",
"tslib": "^2.0.0",
"zone.js": "~0.11.3",
"firebase": "^7.0 || ^8.0"
},
"devDependencies": {
"#angular-devkit/build-angular": "~0.1102.13",
"#angular/cli": "~11.2.15",
"#angular/compiler-cli": "~11.2.14",
"#types/jasmine": "~3.6.0",
"#types/node": "^12.11.1",
"codelyzer": "^6.0.0",
"jasmine-core": "~3.6.0",
"jasmine-spec-reporter": "~5.0.0",
"karma": "~6.1.0",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage": "~2.0.3",
"karma-jasmine": "~4.0.0",
"karma-jasmine-html-reporter": "~1.5.0",
"protractor": "~7.0.0",
"ts-node": "~8.3.0",
"tslint": "~6.1.0",
"typescript": "~4.1.5",
"#angular-devkit/architect": ">= 0.900 < 0.1300",
"firebase-tools": "^8.0.0 || ^9.0.0",
"fuzzy": "^0.1.3",
"inquirer": "^6.2.2",
"inquirer-autocomplete-prompt": "^1.0.1",
"open": "^7.0.3",
"jsonc-parser": "^3.0.0"
}
}
This error is likely a sign that you've not fully migrated to v9 Firebase.
v9 Firebase
Examples of v9 Firebase code
https://dev.to/jdgamble555/angular-12-with-firebase-9-49a0
compat imports as an intermediate step
A simple first-step migration will require changing imports to compat versions.
This keeps code working but you'll not benefit from v9 tree-shaking.
The compat imports gives APIs compatible with v8 code BUT the provide methods e.g. provideFirebaseApp won't work until all imports are v9 imports i.e. back to not being compat imports.
So until ALL your relevant code is upgraded to v9 use the old way
import { AngularFireAuthModule } from '#angular/fire/compat/auth';
import { AngularFireModule } from '#angular/fire/compat';
import { AngularFirestoreModule } from '#angular/fire/compat/firestore';
import { AngularFireAuthGuardModule } from '#angular/fire/compat/auth-guard';
#NgModule({
declarations: [
...
],
imports: [
...
AngularFireModule.initializeApp(environment.firebase),
AngularFirestoreModule,
AngularFireAuthModule,
AngularFireAuthGuardModule,
],
...
})
export class AppModule { }
Once your code is fully migrated go back to the provide methods:
import { initializeApp, provideFirebaseApp } from '#angular/fire/app';
import { provideAuth, getAuth } from '#angular/fire/auth';
import { provideFirestore, getFirestore } from '#angular/fire/firestore';
#NgModule({
declarations: [
...
],
imports: [
...
// firebase
provideFirebaseApp(() => initializeApp(environment.firebase)),
provideAuth(() => getAuth()),
provideFirestore(() => getFirestore()),

dotenv values not loaded in nextjs

I am struggling to load my .env file in my NextJS app. Here is my code:
My .env is in root /
My index.js is in /pages/index.js
Here is my index.js:
require("dotenv").config({ path: __dirname + '/../.env' })
import React, {Component} from 'react'
import Layout from '../components/layout'
import axios from 'axios'
class Import extends Component{
uploadCSV = (evt) => {
evt.preventDefault();
const uploadURL = process.env.MY_UPLOAD_URL
let data = new FormData(evt.target)
axios.post(uploadURL, data, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then((res) => {
console.log(res)
})
}
render() {
return (
<div>
<Layout title="Import Chatbot Intents" description="Import Chatbot Intents">
<form onSubmit={this.uploadCSV} name="import_csv" className="import_csv">
<h2>Import CSV</h2>
<div className="form-group">
<label htmlFor="csv_file">Upload file here: </label>
<input type="file" name="csv_file" id="csv_file" ref="csv_file" />
</div>
<div className="form-group">
<input type="hidden" id="customer_id" name="customer_id" ref="customer_id" value="1"/>
<button className="btn btn-success">Submit</button>
</div>
</form>
</Layout>
</div>
)
}
}
export default Import
I observe that I can print out .env content in render() function, but I cannot do that in uploadCSV function.
For your info:
using just require("dotenv").config() doesn't work
using require("dotenv").config({path: "../"}) doesn't work
Updated
My env-config.js:
module.exports = {
'CSV_UPLOAD_URL': "http://localhost:3000/uploadcsv"
}
My babel.config.js:
const env = require('./env-config')
console.log(env)
module.exports = function(api){
// console.log({"process": process.env})
api.cache(false)
const presets = [
"next/babel",
"#zeit/next-typescript/babel"
]
const plugins = [
"#babel/plugin-transform-runtime",
[
'transform-define',
env
]
]
return { presets, plugins }
}
My package.json
{
"name": "Botadmin",
"scripts": {
"dev": "next -p 3001",
"build": "next build",
"start": "next start"
},
"dependencies": {
"#babel/runtime": "^7.1.5",
"#zeit/next-less": "^1.0.1",
"#zeit/next-typescript": "^1.1.1",
"#zeit/next-workers": "^1.0.0",
"axios": "^0.18.0",
"forever": "^0.15.3",
"less": "^3.8.1",
"multer": "^1.4.1",
"next": "7.0.2",
"nprogress": "^0.2.0",
"papaparse": "^4.6.2",
"react": "16.6.3",
"react-dom": "16.6.3",
"typescript": "^3.1.6",
"worker-loader": "^2.0.0"
},
"devDependencies": {
"#babel/plugin-transform-runtime": "^7.1.0",
"babel-plugin-transform-define": "^1.3.0",
"dotenv": "^6.1.0",
"fork-ts-checker-webpack-plugin": "^0.4.15"
}
}
The Error:
Module build failed (from ./node_modules/next/dist/build/webpack/loaders/next-babel-loader.js):
TypeError: Property property of MemberExpression expected node to be of a type ["Identifier","PrivateName"] but instead got "StringLiteral"
If you want to use env in Nextjs
Install babel-plugin-transform-define
create the env-config.js file and define your variables
const prod = process.env.NODE_ENV === 'production'
module.exports = {
'process.env.BACKEND_URL': prod ? 'https://api.example.com' : 'https://localhost:8080'
}
Create the .babelrc.js file
const env = require('./env-config.js')
module.exports = {
presets: ['next/babel'],
plugins: [['transform-define', env]]
}
Now you have access to the env in your code
process.env.BACKEND_URL
Alternatives: next-env
As of Next.js 9.4, there is a built-in solution for setting environment variables https://nextjs.org/docs/basic-features/environment-variables
Thanks for #Alex for the answer. Another way to solve the same problem is to install dotenv-webpack using npm install -D dotenv-webpack.
Once installed. edit next.config.js:
require('dotenv').config()
const Dotenv = require('dotenv-webpack')
const path = require('path')
const withTypescript = require('#zeit/next-typescript')
const withWorkers = require('#zeit/next-workers')
const withLess = require('#zeit/next-less')
module.exports = withWorkers(withLess(withTypescript({
context: __dirname,
generateEtags: false,
entry: './pages/index.js',
distDir: 'build',
pageExtensions: ['js', 'jsx', 'ts', 'tsx'],
cssModules: false,
webpack: (config, options) => {
config.plugins = config.plugins || []
config.plugins = [
...config.plugins,
// Read the .env file
new Dotenv({
path: path.join(__dirname, '.env'),
systemvars: true
})
]
// Fixes npm packages that depend on `fs` module
config.node = {
fs: 'empty'
}
return config
}
})))
I know I'm a bit late, but, you can just install dotenv and use it inside of your next.config.js file
require("dotenv").config();
const environment = process.env.NODE_ENV || "dev";
if you need to replicate next.js env loading in other files (setupTests.ts, next-logger.config.js) do this:
const { loadEnvConfig } = require('#next/env')
loadEnvConfig(__dirname, true, {
info: () => null,
error: console.error,
})

Uncaught (in promise): Error: StaticInjectorError[Service]

I am new to angular. I have created an webapplication using vs2015 and latest angular packages.
When i try to call my service from component on button click event then i am getting below error in browser console window.
Error: -
ERROR Error: Uncaught (in promise): Error: StaticInjectorError[ViewCountService]:
StaticInjectorError[ViewCountService]:
NullInjectorError: No provider for ViewCountService!
Error: StaticInjectorError[ViewCountService]:
StaticInjectorError[ViewCountService]:
NullInjectorError: No provider for ViewCountService!
at _NullInjector.get (injector.js:31)
at resolveToken (injector.js:387)
at tryResolveToken (injector.js:330)
at StaticInjector.get (injector.js:170)
at resolveToken (injector.js:387)
at tryResolveToken (injector.js:330)
at StaticInjector.get (injector.js:170)
at resolveNgModuleDep (ng_module.js:103)
at NgModuleRef_.get (refs.js:1037)
at resolveDep (provider.js:455)
at _NullInjector.get (injector.js:31)
at resolveToken (injector.js:387)
at tryResolveToken (injector.js:330)
at StaticInjector.get (injector.js:170)
at resolveToken (injector.js:387)
at tryResolveToken (injector.js:330)
at StaticInjector.get (injector.js:170)
at resolveNgModuleDep (ng_module.js:103)
at NgModuleRef_.get (refs.js:1037)
at resolveDep (provider.js:455)
at resolvePromise (zone.js:824)
at resolvePromise (zone.js:795)
at zone.js:873
at ZoneDelegate.invokeTask (zone.js:425)
at Object.onInvokeTask (ng_zone.js:575)
at ZoneDelegate.invokeTask (zone.js:424)
at Zone.runTask (zone.js:192)
at drainMicroTaskQueue (zone.js:602)
at ZoneTask.invokeTask [as invoke] (zone.js:503)
at invokeTask (zone.js:1540)
defaultErrorLogger # errors.js:48
ErrorHandler.handleError # error_handler.js:90
next # application_ref.js:311
schedulerFn # event_emitter.js:156
SafeSubscriber.__tryOrUnsub # Subscriber.ts:254
SafeSubscriber.next # Subscriber.ts:204
Subscriber._next # Subscriber.ts:135
Subscriber.next # Subscriber.ts:95
Subject.next # Subject.ts:61
EventEmitter.emit # event_emitter.js:131
(anonymous) # ng_zone.js:605
ZoneDelegate.invoke # zone.js:392
Zone.run # zone.js:142
NgZone.runOutsideAngular # ng_zone.js:404
onHandleError # ng_zone.js:605
ZoneDelegate.handleError # zone.js:396
Zone.runGuarded # zone.js:158
_loop_1 # zone.js:702
api.microtaskDrainDone # zone.js:711
drainMicroTaskQueue # zone.js:610
ZoneTask.invokeTask # zone.js:503
invokeTask # zone.js:1540
globalZoneAwareCallback # zone.js:1566
my app.module.ts: -
import { NgModule, Injectable } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { RouterModule, Routes } from '#angular/router';
import { HttpModule } from '#angular/http';
import { ModalModule } from 'ngx-modialog';
import { BootstrapModalModule, Modal, bootstrap4Mode } from 'ngx-modialog/plugins/bootstrap';
import { AppComponent } from './app.component';
import { ExportToPdfComponent } from './exportTopdf/exportTopdf.component';
import { InvalidPageComponent } from './invalidPage/invalidPage.component';
import { ViewCountService } from './Service/viewsCount.component';
const appRoutes: Routes = [
{ path: 'home', component: AppComponent },
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'export', component: ExportToPdfComponent },
{ path: '**', component: InvalidPageComponent }
];
#NgModule({
imports: [
BrowserModule,
HttpModule,
RouterModule.forRoot(appRoutes),
ModalModule.forRoot(),
BootstrapModalModule
],
declarations: [
AppComponent,
ExportToPdfComponent,
InvalidPageComponent
],
bootstrap: [
AppComponent
],
providers: [
ViewCountService
]
})
export class AppModule { }
exportTopdf.component.ts file: -
import { Component, ViewContainerRef, ViewEncapsulation } from '#angular/core';
import { ViewCountService } from '../Service/ViewsCount.component';
import { Overlay } from 'ngx-modialog';
import { Modal } from 'ngx-modialog/plugins/bootstrap';
#Component({
selector: 'export-to-pdf',
templateUrl: 'app/exportTopdf/exportTopdf.component.html',
})
export class ExportToPdfComponent {
name: string;
fields: any;
constructor(public modal: Modal, private ViewCountService: ViewCountService) {
debugger;
this.fields = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }];
}
getViewCount(): void {
debugger;
this.ViewCountService.getViewCount()
.then(data => {
this.name = data;
console.log("I CANT SEE DATA HERE: ", this.name)
});
}
}
my service code: -
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import { Observable } from 'rxjs/Rx';
#Injectable()
export class ViewCountService {
constructor(private http: Http) {
}
getViewCount() {
return this.http.get('api/Tableau/GetViewsCount')
.map(response => response.json() as string).toPromise();
}
getDataObservable(url: string) {
return this.http.get('api/Tableau/GetViewsCount')
.map(data => {
data.json();
console.log("I CAN SEE DATA HERE: ", data.json());
});
}
}
system.config.js: -
/**
* System configuration for Angular samples
* Adjust as necessary for your application needs.
*/
(function (global) {
System.config({
transpiler: 'typescript',
//typescript compiler options
typescriptOptions: {
emitDecoratorMetadata: true
},
paths: {
// paths serve as alias
'npm:': '/node_modules/'
},
// map tells the System loader where to look for things
map: {
// our app is within the app folder
'app': 'app',
// angular bundles
'#angular/core': 'npm:#angular/core/bundles/core.umd.js',
'#angular/common': 'npm:#angular/common/bundles/common.umd.js',
'#angular/compiler': 'npm:#angular/compiler/bundles/compiler.umd.js',
'#angular/platform-browser': 'npm:#angular/platform-browser/bundles/platform-browser.umd.js',
'#angular/platform-browser-dynamic': 'npm:#angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
'#angular/http': 'npm:#angular/http/bundles/http.umd.js',
'#angular/router': 'npm:#angular/router/bundles/router.umd.js',
'#angular/forms': 'npm:#angular/forms/bundles/forms.umd.js',
// other libraries
'rxjs': 'npm:rxjs',
'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js',
'ngx-modialog': 'npm:ngx-modialog/bundle/ngx-modialog.umd.min.js',
'ngx-modialog/plugins/bootstrap': 'npm:ngx-modialog/plugins/bootstrap/bundle/ngx-modialog-bootstrap.umd.min.js'
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
app: {
defaultExtension: 'js',
meta: {
'./*.js': {
loader: 'systemjs-angular-loader.js'
}
}
},
rxjs: {
defaultExtension: 'js'
}
}
});
})(this);
package.json: -
{
"name": "angular-quickstart",
"version": "1.0.0",
"description": "QuickStart package.json from the documentation, supplemented with testing support",
"scripts": {
"build": "tsc -p src/",
"build:watch": "tsc -p src/ -w",
"build:e2e": "tsc -p e2e/",
"serve": "lite-server -c=bs-config.json",
"serve:e2e": "lite-server -c=bs-config.e2e.json",
"prestart": "npm run build",
"start": "concurrently \"npm run build:watch\" \"npm run serve\"",
"pree2e": "npm run build:e2e",
"e2e": "concurrently \"npm run serve:e2e\" \"npm run protractor\" --kill-others --success first",
"preprotractor": "webdriver-manager update",
"protractor": "protractor protractor.config.js",
"pretest": "npm run build",
"test": "concurrently \"npm run build:watch\" \"karma start karma.conf.js\"",
"pretest:once": "npm run build",
"test:once": "karma start karma.conf.js --single-run",
"lint": "tslint ./src/**/*.ts -t verbose"
},
"keywords": [],
"author": "",
"license": "MIT",
"dependencies": {
"#angular/common": "~5.0.3",
"#angular/compiler": "~5.0.3",
"#angular/core": "~5.0.3",
"#angular/forms": "~5.0.3",
"#angular/http": "~5.0.3",
"#angular/platform-browser": "~5.0.3",
"#angular/platform-browser-dynamic": "~5.0.3",
"#angular/router": "~5.0.3",
"angular-in-memory-web-api": "~0.5.1",
"bootstrap": "^3.3.7",
"core-js": "^2.4.1",
"ngx-modialog": "^5.0.0",
"rxjs": "5.5.2",
"systemjs": "0.20.19",
"zone.js": "^0.8.4"
},
"devDependencies": {
"concurrently": "^3.2.0",
"lite-server": "^2.2.2",
"typescript": "~2.6.1",
"canonical-path": "0.0.2",
"tslint": "^5.8.0",
"lodash": "^4.16.4",
"jasmine-core": "~2.8.0",
"karma": "^1.3.0",
"karma-chrome-launcher": "^2.0.0",
"karma-cli": "^1.0.1",
"karma-jasmine": "^1.0.2",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "~5.2.0",
"rimraf": "^2.5.4",
"#types/node": "^8.0.53",
"#types/jasmine": "2.8.2"
},
"repository": {}
}
Thanks in advance for your valuable feedbacks and comments.
Look at your impors
app.module.ts
import { ViewCountService } from './Service/viewsCount.component';
exportTopdf.component.ts
import { ViewCountService } from '../Service/ViewsCount.component';
Since Systemjs is case-sensitive(See Service instance is not available for child component in angular2)
looks like you're importing different modules
ViewsCount
|
viewsCount
So choose only one option to import your service
app.module.ts
import { ViewCountService } from './Service/viewsCount.component';
exportTopdf.component.ts
import { ViewCountService } from '../Service/viewsCount.component';
^
instead of V
Read also style guide to better understanding how to name your files
If you are using Angular 4.3+ until 5 you will need to import HttpClient in your app.module from the new library
> import { HttpClientModule } from '#angular/common/http';
imports: [
YModule,
XModule,
HttpClientModule
],
In your service :
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs/Rx';
#Injectable()
export class ViewCountService {
constructor(private http: HttpClient ) {
}
getViewCount() {
return this.http.get('api/Tableau/GetViewsCount');
}
...
}
In your component:
getViewCount(): void {
this.ViewCountService.getViewCount()
.subscribe(
data =>{console.log(data);//your data},
err=>{console.log(err);},
() => {console.log("Done loading");}
);
}
I was facing the same issue then I have added below line in app.module and it worked for me.
import { HttpClientModule } from ‘#angular/common/http’;
And add it to the
#NgModule({ imports: [ ..., HttpClientModule,... ]
It doesn't look to be solved yet:
https://github.com/angular/angular/issues/20339
As a work around, try to make all your constructor() functions without parameters by extracting the as properties.
ExportToPdfComponent:
import { Component, ViewContainerRef, ViewEncapsulation } from '#angular/core';
import { ViewCountService } from '../Service/ViewsCount.component';
import { Overlay } from 'ngx-modialog';
import { Modal } from 'ngx-modialog/plugins/bootstrap';
#Component({
selector: 'export-to-pdf',
templateUrl: 'app/exportTopdf/exportTopdf.component.html',
})
export class ExportToPdfComponent {
name: string;
fields: any;
modal: Modal;
ViewCountService: ViewCountService;
constructor() {
debugger;
this.fields = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }];
}
getViewCount(): void {
debugger;
this.ViewCountService.getViewCount()
.then(data => {
this.name = data;
console.log("I CANT SEE DATA HERE: ", this.name)
});
}
}
ViewCountService:
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import { Observable } from 'rxjs/Rx';
#Injectable()
export class ViewCountService {
private http: Http;
constructor() {
}
getViewCount() {
return this.http.get('api/Tableau/GetViewsCount')
.map(response => response.json() as string).toPromise();
}
getDataObservable(url: string) {
return this.http.get('api/Tableau/GetViewsCount')
.map(data => {
data.json();
console.log("I CAN SEE DATA HERE: ", data.json());
});
}
}
import { HttpClientModule, HTTP_INTERCEPTORS } from '#angular/common/http';
imports: [
BrowserModule,
FormsModule,
HttpClientModule,
routing
],
add this into your app.module.ts file

Resources