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

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

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.

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()),

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

Material 2 attributes in Angular 4 aren't working with webpack, ASP.NET

I'm trying to get Material 2 to work with Angular 4.4.6 using webpack in an ASP.NET Core 2 web application. I get no errors but I currently get no styling and the mat-button attribute has no effect on the output DOM.
I have done the following:
Environment is as follows:
Visual Studio (Professional) 2017 version 15.4.0
ASP.NET Core 2 web application with Angular, from VS template
Update #angular packages to ^4.4.6 in NPM and restore packages
"#angular/animations": "^4.4.6",
"#angular/common": "^4.4.6",
"#angular/compiler": "^4.4.6",
"#angular/compiler-cli": "^4.4.6",
"#angular/core": "^4.4.6",
"#angular/forms": "^4.4.6",
"#angular/http": "^4.4.6",
"#angular/platform-browser": "^4.4.6",
"#angular/platform-browser-dynamic": "^4.4.6",
"#angular/platform-server": "^4.4.6",
"#angular/router": "^4.4.6",
Per the Material guide, run the following command in the project directory:
npm install --save #angular/material #angular/cdk
Update webpack.config.vendor.js to add the following lines to the treeShakableModules array, just after '#angular/router':
'#angular/material',
'#angular/material/prebuilt-themes/deeppurple-amber.css',
In app.module.browser.ts, import the module:
import { MatButtonModule } from '#angular/material';
#NgModule({
bootstrap: [ AppComponent ],
imports: [
BrowserModule,
MatButtonModule,
AppModuleShared
],
providers: [
{ provide: 'BASE_URL', useFactory: getBaseUrl }
]
})
In home.component.html, add the following line at the end of the file:
<button mat-raised-button>This is a button</button>
From the project directory, run webpack to update the vendor files:
webpack --config webpack.config.vendor.js
Build and run the application
Observe the home page button is not styled. There are no errors in the console suggesting missing styles or invalid attributes.
I have the following configuration:
Angular 4.4.6
Material 2.0.0-beta.12
Windows 10 Professional
TypeScript 2.4.1 (NPM)
Chrome Version 61.0.3163.100 (Official Build) (64-bit)
Verified the styles do exist, as specifying class="mat-raised-button" on the button has an effect (though it does not look like the raised button) it does change the interior styling of the button.
I note that the attribute does not appear to have any effect on the styling or content of the output HTML (versus what I see when inspecting the elements on the guide website), suggesting that something has gone wrong with the setup of the module, but I can't for the life of me figure out what that might be.
EDIT: By request, here is the webpack.config.vendor.js up to the boilerplate:
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const merge = require('webpack-merge');
const treeShakableModules = [
'#angular/animations',
'#angular/common',
'#angular/compiler',
'#angular/core',
'#angular/forms',
'#angular/http',
'#angular/platform-browser',
'#angular/platform-browser-dynamic',
'#angular/router',
'zone.js',
];
const nonTreeShakableModules = [
'#angular/cdk',
'#angular/material',
'#angular/material/button',
'#angular/material/prebuilt-themes/deeppurple-amber.css',
'bootstrap',
'bootstrap/dist/css/bootstrap.css',
'es6-promise',
'es6-shim',
'event-source-polyfill',
'jquery',
];
const allModules = treeShakableModules.concat(nonTreeShakableModules);
module.exports = (env) => {
const extractCSS = new ExtractTextPlugin('vendor.css');
const isDevBuild = !(env && env.prod);
const sharedConfig = {
stats: { modules: false },
resolve: { extensions: [ '.js' ] },
module: {
rules: [
{ test: /\.(png|woff|woff2|eot|ttf|svg)(\?|$)/, use: 'url-loader?limit=100000' }
]
},
output: {
publicPath: 'dist/',
filename: '[name].js',
library: '[name]_[hash]'
},
plugins: [
new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }), // Maps these identifiers to the jQuery package (because Bootstrap expects it to be a global variable)
new webpack.ContextReplacementPlugin(/\#angular\b.*\b(bundles|linker)/, path.join(__dirname, './ClientApp')), // Workaround for https://github.com/angular/angular/issues/11580
new webpack.ContextReplacementPlugin(/angular(\\|\/)core(\\|\/)#angular/, path.join(__dirname, './ClientApp')), // Workaround for https://github.com/angular/angular/issues/14898
new webpack.IgnorePlugin(/^vertx$/) // Workaround for https://github.com/stefanpenner/es6-promise/issues/100
]
};
... boilerplate follows this ...
So somewhat counterintuitively, the solution requires that the module importing be done in app.module.shared.ts, not app.module.browser.ts. If you are using the default Angular template, use the same steps as above, except for step 5, do the following:
Edit app.module.shared.ts to add the MatButtonModule module as an import, as follows:
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { FormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import { RouterModule } from '#angular/router';
import { MatButtonModule } from '#angular/material/button';
import { AppComponent } from './components/app/app.component';
import { NavMenuComponent } from './components/navmenu/navmenu.component';
import { HomeComponent } from './components/home/home.component';
import { FetchDataComponent } from './components/fetchdata/fetchdata.component';
import { CounterComponent } from './components/counter/counter.component';
#NgModule({
declarations: [
AppComponent,
NavMenuComponent,
CounterComponent,
FetchDataComponent,
HomeComponent
],
imports: [
CommonModule,
HttpModule,
FormsModule,
MatButtonModule,
RouterModule.forRoot([
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'counter', component: CounterComponent },
{ path: 'fetch-data', component: FetchDataComponent },
{ path: '**', redirectTo: 'home' }
])
]
})
export class AppModuleShared {
}
Note also it is not necessary to add #angular/cdk or #angular/material/button to the modules list in webpack.config.vendor.js. It is sufficient to add the ones described in the guide.
See: https://github.com/angular/material2/issues/7997
According to official docs Here
You've to Import theming to your Global style file this is as simple as including one line in your styles.css file:
#import '~#angular/material/prebuilt-themes/deeppurple-amber.css';
or Alternatively, you can just reference the file directly.
Available pre-built themes:
deeppurple-amber.css
indigo-pink.css
pink-bluegrey.css
purple-green.css

router-outlet is not a known element

The following code works:
/*app.module.ts*/
import { NgModule } from '#angular/core';
import { HttpModule } from '#angular/http';
import { AppComponent } from './app.component';
import { LetterRecall } from './letterRecall/letterRecall.component';
#NgModule({
imports: [BrowserModule, HttpModule],
declarations: [AppComponent, LetterRecall],
bootstrap: [AppComponent],
})
export class AppModule {}
/*app.component.ts*/
import {Component} from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: 'app/app.component.html'
})
export class AppComponent { }
/*app.component.html*/
<h3>Title</h3>
<letter-recall></letter-recall>
Following the Angular Routing Tutorial here: https://angular.io/docs/ts/latest/tutorial/toh-pt5.html
I modified my code to:
/*index.html*/
<head>
<base href="/">
/*app.module.ts*/
import { NgModule } from '#angular/core';
import { HttpModule } from '#angular/http';
import { RouterModule } from '#angular/router';
import { AppComponent } from './app.component';
import { LetterRecall } from './letterRecall/letterRecall.component';
#NgModule({
imports: [BrowserModule,
HttpModule,
RouterModule.forRoot([
{ path: 'letters', component: LetterRecall }
])],
declarations: [AppComponent, LetterRecall],
bootstrap: [AppComponent],
})
export class AppModule {}
/*app.component.ts*/
import {Component} from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: 'app/app.component.html'
})
export class AppComponent { }
/*app.component.html*/
<h3>Title</h3>
<a routerLink="/letters">Letters</a>
<router-outlet></router-outlet>
At this point I get the following error:
"Unhandled Promise rejection: Template parse errors: 'router-outlet'
is not a known element:
1. If 'router-outlet' is an Angular component, then verify that it is part of this module. ....."
I am using the following versions:
"#angular/common": "2.4.0",
"#angular/compiler": "2.4.0",
"#angular/core": "2.4.0",
"#angular/forms": "2.4.0",
"#angular/http": "2.4.0",
"#angular/platform-browser": "2.4.0",
"#angular/platform-browser-dynamic": "2.4.0",
"#angular/router": "3.4.0"
All of the other answers on SO indicate I need to import RouterModule but as you can see above, I am doing this as prescribed in the tutorial.
Any suggestions on where I can look for the source of this error? I started off using John Papa's First Look tutorial on PluralSight but it looks like that code is a little old now. That's when I stripped all of that out and went bare-bones through the tutorial and I get this error... I am not sure where to turn next.
Like Erion said: In my case I did (added) two things in app.component.spec.ts:
import { RouterTestingModule } from '#angular/router/testing';
...
TestBed.configureTestingModule({
imports: [ RouterTestingModule ],
declarations: [
AppComponent
],
}).compileComponents();
Probably I'm late here, but since I got the exaclty same issue and found an answer here.
Are you using angular-cli?
https://github.com/angular/angular-cli/pull/3252/files#diff-badc0de0550cb14f40374a6074eb2a8b
In my case I just had to import my new router module in the app.component.spec.ts
The js import and NgModule import.
Then restart the test server.
The angular router directive is part of part of lib: #angular/router and it acts a placeholder which is filled up by angular state.
Here I am dividing two file separately i.e. app.module.ts and app.router.ts
Here app.router.ts
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { MainComponent } from './components/main/main.component';
import { AppComponent } from './app.component';
const appRoutes: Routes = [
{ path: 'main', component: MainComponent },
{ path: '', redirectTo: '/main', pathMatch: 'full' }
];
#NgModule({
imports: [
RouterModule.forRoot(appRoutes)
],
exports: [
RouterModule
]
})
export class AppRouter { }
Here app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppRouter } from './app.router';
import { AppComponent } from './app.component';
import { MainComponent } from './components/main/main.component';
#NgModule({
declarations: [
AppComponent,
MainComponent
],
imports: [
BrowserModule,
AppRouter
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Now you can use <router-outlet></router-outlet> in your app.component.ts file and won't show any error

Resources