Network Error: req.headers.forEach Apollo Client Angular4 - javascript

Trying to query my graphql endpoint, which is accessible with a postman call, using the ApolloClient.Query call provided by the Apollo Client and return results. Following the guidelines from the docs here, I should be able to do something quick and crude like the following in a custom angular 4 component:
import { Component } from '#angular/core';
import { AuthService } from '../services/auth.service';
import { User } from '../models/user';
import { Apollo } from 'apollo-angular';
import gql from 'graphql-tag';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent {
user: User = new User();
constructor(private auth: AuthService, private apollo: Apollo) {}
onLogin(): void {
this.apollo.query({
context: {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
opts: {
mode: 'no-cors',
}
},
query: gql`{
allUsers {
id
emailAddress
password
}
}`}).subscribe(
(response) => console.log(response),
(error) => console.log(error),
() => console.log('completed!')
);
}
}
with the following Apollo Client creation in my main app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { RouterModule } from '#angular/router';
import {HttpClientModule} from '#angular/common/http';
import { FormsModule } from '#angular/forms';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { LoginComponent } from './login/login.component';
import { AuthService } from './services/auth.service';
import { RegisterComponent } from './register/register.component';
import { StatusComponent } from './status/status.component';
import { ApolloModule, Apollo } from 'apollo-angular';
import { HttpLinkModule, HttpLink } from 'apollo-angular-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
#NgModule({
declarations: [
AppComponent,
HeaderComponent,
LoginComponent,
RegisterComponent,
StatusComponent
],
imports: [
BrowserModule,
HttpClientModule,
FormsModule,
ApolloModule,
HttpLinkModule,
RouterModule.forRoot([
{ path: 'login', component: LoginComponent },
{ path: 'register', component: RegisterComponent },
{ path: 'status', component: StatusComponent }
])
],
providers: [AuthService],
bootstrap: [AppComponent]
})
export class AppModule {
constructor(
apollo: Apollo,
httpLink: HttpLink
) {
apollo.create({
link: httpLink.create({ withCredentials: false,
uri: 'http://localhost:8080/graphql'}),
cache: new InMemoryCache()
});
}
}
However, in my debug console I am getting the following error. Thoughts? Scroll below to see the versioning of my javascript libraries
Error: Network error: req.headers.forEach is not a function
at new ApolloError (ApolloError.js:34)
at QueryManager.js:277
at QueryManager.js:655
at Array.forEach (<anonymous>)
at QueryManager.js:654
at Map.forEach (<anonymous>)
at QueryManager.webpackJsonp.../../../../apollo-client/core/QueryManager.js.QueryManager.broadcastQueries (QueryManager.js:649)
at QueryManager.js:226
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:392)
package.json
{
"name": "frontend",
"version": "0.0.0",
"license": "MIT",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"#angular/animations": "^4.0.0",
"#angular/common": "^4.0.0",
"#angular/compiler": "^4.0.0",
"#angular/core": "^4.0.0",
"#angular/forms": "^4.0.0",
"#angular/http": "^4.0.0",
"#angular/platform-browser": "^4.0.0",
"#angular/platform-browser-dynamic": "^4.0.0",
"#angular/router": "^4.0.0",
"apollo-angular": "^1.0.0",
"apollo-angular-link-http": "^1.0.1",
"apollo-cache-inmemory": "^1.1.1",
"apollo-client": "^2.0.3",
"core-js": "^2.4.1",
"graphql": "^0.11.7",
"graphql-tag": "^2.5.0",
"rxjs": "^5.4.1",
"zone.js": "^0.8.14"
},
"devDependencies": {
"#angular/cli": "1.2.3",
"#angular/compiler-cli": "^4.0.0",
"#angular/language-service": "^4.0.0",
"#types/jasmine": "~2.5.53",
"#types/jasminewd2": "~2.0.2",
"#types/node": "~6.0.60",
"codelyzer": "~3.0.1",
"jasmine-core": "~2.6.2",
"jasmine-spec-reporter": "~4.1.0",
"karma": "~1.7.0",
"karma-chrome-launcher": "~2.1.1",
"karma-cli": "~1.0.1",
"karma-coverage-istanbul-reporter": "^1.2.1",
"karma-jasmine": "~1.1.0",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "~5.1.2",
"ts-node": "~3.0.4",
"tslint": "~5.3.2",
"typescript": "~2.3.3"
}
}

I had the same problem. What solved it for me was to swap out the headers to be inserted into the middleware instead, and then pass the middleware as a concat() result into link.
https://www.apollographql.com/docs/angular/basics/network-layer.html
const authMiddleware = new ApolloLink((operation, forward) => {
// add the authorization to the headers
operation.setContext({
headers: new HttpHeaders().set('Authorization', yourToken)
});
return forward(operation);
});
... <other code>
apollo.create({
link: concat(authMiddleware, http),
cache: new InMemoryCache()
});
Of course, you can probably swap Authorization for Content-Type and any other header you want.

Related

Compiler fails - ERROR in No NgModule metadata found for 'AppModule'

Compile fails with this error. I have looked through all the posts with similar titles and not found anything helpful yet. Angular 7. I was trying to update some dependencies to resolve prod vulnerabilities, the change list for this was moving angular-devkit/build-angular to dev dependencies, removing abandoned and unused packages, adding ngx-toastr 10, upgrading jasmine-core from 3.3 to 3.8.
I have deleted, cleared cache, and reinstalled all node packages and then tried specifically doing that to angular/cli (7.1.1) and webpack (4.12.0). Edited+saved a random ts file. Added app/app.module.ts specifically to tsconfig.app.json's files param and include param. Added strictMetadataEmit:false to tsconfig.json and tsconfig.app.json compilerOptions (unknown compiler param error).
tsconfig.json
{
"compileOnSave": false,
"compilerOptions": {
"outDir": "./dist/out-tsc",
"baseUrl": "./src",
"sourceMap": true,
"declaration": false,
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es5",
"typeRoots": [
"node_modules/#types"
],
"types": [
"jasmine"
],
"lib": [
"es2017",
"dom"
],
"paths": {
"#app/*": [ "app/*" ],
"#env/*": [ "environments/*" ]
}
},
"include": [
"src/**/*"
]
}
tsconfig.app.json
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/app",
"module": "es2015",
"baseUrl": "",
"types": []
},
"exclude": [
"test.ts",
"**/*.spec.ts"
],
"include": [
"./**/*"
]
}
package.json
{
"name": "pds.ui",
"version": "0.0.0",
"license": "MIT",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e",
"inc-ram": "set NODE_OPTIONS=--max-old-space-size=12000",
"build-prod": "npm run-script inc-ram && ng build --prod --source-map false --aot"
},
"private": true,
"dependencies": {
"#angular/animations": "^7.1.3",
"#angular/common": "^7.1.3",
"#angular/compiler": "^7.1.3",
"#angular/core": "^7.1.3",
"#angular/forms": "^7.1.3",
"#angular/http": "^7.1.3",
"#angular/platform-browser": "^7.1.3",
"#angular/platform-browser-dynamic": "^7.1.3",
"#angular/router": "^7.1.3",
"#progress/kendo-angular-buttons": "^4.1.1",
"#progress/kendo-angular-dateinputs": "^3.5.2",
"#progress/kendo-angular-dialog": "^3.1.2",
"#progress/kendo-angular-dropdowns": "^3.0.2",
"#progress/kendo-angular-excel-export": "^2.1.0",
"#progress/kendo-angular-grid": "^3.5.0",
"#progress/kendo-angular-inputs": "^3.1.3",
"#progress/kendo-angular-intl": "^1.3.1",
"#progress/kendo-angular-l10n": "^1.1.0",
"#progress/kendo-angular-layout": "^3.1.1",
"#progress/kendo-angular-pdf-export": "^1.0.4",
"#progress/kendo-angular-upload": "^4.1.2",
"#progress/kendo-data-query": "^1.2.0",
"#progress/kendo-drawing": "^1.5.5",
"#progress/kendo-theme-bootstrap": "^2.13.4",
"#progress/kendo-theme-default": "^2.53.1",
"angular-calendar": "^0.27.15",
"angular2-draggable": "^2.1.1",
"bootstrap": "^4.0.0",
"classlist.js": "^1.1.20150312",
"core-js": "^2.5.3",
"date-fns": "^1.30.1",
"font-awesome": "^4.7.0",
"guid-typescript": "^1.0.9",
"jasmine-tfs-reporter": "^1.0.2",
"json2typescript": "1.0.6",
"moment": "^2.20.1",
"ngx-bootstrap": "^3.0.0",
"ngx-permissions": "^6.0.1",
"ngx-quill": "^5.2.0",
"ngx-toastr": "^10.1.0",
"node-sass": "^4.7.2",
"npm": "^6.4.1",
"quill": "^1.3.7",
"rxjs": "^6.2.1",
"rxjs-compat": "^6.2.1",
"ts-helpers": "^1.1.2",
"typescript": "3.2.4",
"web-animations-js": "^2.3.1",
"zone.js": "^0.8.20"
},
"devDependencies": {
"#angular-devkit/build-angular": "^0.11.4",
"#angular-devkit/build-optimizer": "^0.11.3",
"#angular/cli": "^7.1.1",
"#angular/compiler-cli": "^7.1.3",
"#types/applicationinsights-js": "1.0.9",
"#types/jasmine": "3.3.1",
"#types/node": "^10.3.2",
"codelyzer": "^4.1.0",
"html-webpack-plugin": "^3.2.0",
"jasmine-core": "~3.8.0",
"jasmine-spec-reporter": "^4.2.1",
"karma": "~3.1.3",
"karma-chrome-launcher": "~2.2.0",
"karma-cli": "~2.0.0",
"karma-coverage-istanbul-reporter": "^2.0.1",
"karma-jasmine": "~2.0.1",
"karma-jasmine-html-reporter": "^1.1.0",
"protractor": "^5.4.1",
"ts-node": "~7.0.1",
"tslint": "~5.11.0",
"webpack": "^4.12.0"
},
"engines": {
"node": ">= 8.6.0",
"npm": ">= 5.4.2"
}
}
app.module.ts
// Angular
import { NgModule, OnInit, APP_INITIALIZER } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { BrowserModule, Title } from '#angular/platform-browser';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations';
import { Injector } from '#angular/core';
// Kendo & 3rd Party
import { InputsModule } from '#progress/kendo-angular-inputs';
import { ModalModule } from 'ngx-bootstrap';
import { UploadModule } from '#progress/kendo-angular-upload';
import { CoreModule, ConfigService } from '#app/core';
import { SharedModule } from '#app/shared';
// App
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app.routing';
import { HeaderComponent } from './header/header.component';
import { AdminModule } from './admin/admin.module';
import { MasterProjectModule } from './master-project/master-project.module';
import { ContractModule } from './contract/contract.module';
import { FAQComponent } from './shared/faq/faq.component';
import { DashboardModule } from './dashboard/dashboard.module';
import { AngularDraggableModule } from 'angular2-draggable';
// Services
import { RepositoryService } from '#app/shared/repository.service';
import { ServiceLocator } from '#app/shared/service-locator';
import { EmailService } from '#app/shared/email.service';
import { CanDeactivateGuardService } from '#app/shared/candeactivate-guard.service';
import { NavigationEnd, Router, ActivatedRoute } from '#angular/router';
import { MasterProjectRoutingModule } from '#app/master-project/master-project-routing.module';
import { ContractRoutingModule } from '#app/contract/contract-routing.module';
import { DashboardRoutingModule } from '#app/dashboard/dashboard-routing.module';
import { DialogModule } from '#progress/kendo-angular-dialog';
import { NgxPermissionsModule } from 'ngx-permissions';
import { NgxPermissionsService } from 'ngx-permissions';
import { Role } from '#app/core/role';
import { NgxRolesService } from 'ngx-permissions';
import { HttpClientModule, HttpClient } from '#angular/common/http';
import { AcknowledgementsComponent } from './shared/acknowledgements/acknowledgements';
import { ToastrModule } from 'ngx-toastr';
import { ProgressBarComponent } from './shared/ProgressBar/ProgressBar';
import { LoadingBarService } from './shared/LoadingBarService/LoadingBarService';
export function initConfig(config: ConfigService): Function {
return () => config.getAll();
}
#NgModule({
imports: [
FormsModule,
BrowserModule,
HttpClientModule,
AppRoutingModule,
BrowserAnimationsModule,
DashboardModule,
AngularDraggableModule,
DashboardRoutingModule,
AdminModule,
MasterProjectRoutingModule,
MasterProjectModule,
ContractRoutingModule,
ContractModule,
InputsModule,
DialogModule,
UploadModule,
ToastrModule.forRoot(),
NgxPermissionsModule.forRoot(),
// App Core & Shared
CoreModule,
SharedModule,
ModalModule.forRoot()
],
exports: [SharedModule],
declarations: [
AppComponent,
ProgressBarComponent,
HeaderComponent,
FAQComponent,
AcknowledgementsComponent
],
providers: [
Title,
LoadingBarService,
EmailService,
CanDeactivateGuardService,
RepositoryService,
ServiceLocator,
ConfigService,
NgxRolesService,
NgxPermissionsService,
{
provide: APP_INITIALIZER,
useFactory: (http: HttpClient, configService: ConfigService, rs: NgxRolesService, ps: NgxPermissionsService ) => function() {
return configService.getAll().then((config) => {
return http.get(`${config.BaseApiURL}GetMyRoles`,
{ withCredentials: true }).do((roles: any) => {
for (const role of roles.value as Array<Role>) {
rs.addRole(role.Name, role.Permissions);
ps.addPermission(role.Permissions);
}
}).toPromise()
});
},
deps: [HttpClient, ConfigService, NgxRolesService, NgxPermissionsService],
multi: true
}
],
bootstrap: [
AppComponent]
})
export class AppModule implements OnInit {
constructor(
readonly router: Router,
readonly activatedRoute: ActivatedRoute,
readonly titleService: Title,
readonly loadingBarService: LoadingBarService,
private injector: Injector) { // Create global Service Injector.
ServiceLocator.injector = this.injector;
}
}
main.ts
import { enableProdMode } from '#angular/core';
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
import { AppModule } from '#app/app.module';
import { environment } from '#env/environment';
if (environment.production) {
enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule);
I reverted to a previous commit and re-applied the updates while ensuring it still built between each update. Didn't see the error again.

How to fix 'Can't resolve all parameters for ComponentName'

I am trying to run ng serve command for my angular project. It works, it builds but when I want to access to localhost:4200 (my local host angular access) the screen is blank and console says:
Uncaught Error: Can't resolve all parameters for
CreateContractComponent: (?, ?, ?).
Everything worked before I re-checkout project as a new project to my computer. When I deploy app it perfectly works (For example heroku)
I spent 1 day googling and trying something from the different topics, but still bad. If you need/want more files, let me know.
shortly component code:
import { Component, OnInit } from '#angular/core';
import { ContractService } from '../offer-page/contract.service';
import { ActivatedRoute, Router } from '#angular/router';
#Component({
selector: 'app-create-contract',
templateUrl: './create-contract.component.html',
styleUrls: ['./create-contract.component.css']
})
export class CreateContractComponent implements OnInit {
constructor(private contractService: ContractService, private route: ActivatedRoute,private router: Router) {
}
}
contractService shortly
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Contract } from './object-model/contract';
#Injectable()
export class ContractService {
constructor(
private http: HttpClient
) { }
}
What I need is just to run ng serve command and be able to work in dev mode. Now it is possible only with deployment (to heroku).
EDIT for request files:
this is my package.json file
{
"name": "name-of-the-project",
"version": "0.0.0",
"engines": {
"node": "8.9.x",
"npm": "5.5.x"
},
"license": "MIT",
"scripts": {
"ng": "ng",
"start": "node server.js",
"build": "ng build --prod",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e",
"deploy": "git push heroku master",
"postinstall": "ng build --aot -prod"
},
"private": true,
"dependencies": {
"#angular/animations": "^5.0.0",
"#angular/cli": "^1.6.3",
"#angular/common": "^5.0.0",
"#angular/compiler": "^5.0.0",
"#angular/compiler-cli": "^5.1.3",
"#angular/core": "^5.0.0",
"#angular/forms": "^5.0.0",
"#angular/platform-browser": "^5.0.0",
"#angular/platform-browser-dynamic": "^5.0.0",
"#angular/router": "^5.0.0",
"#angular/http": "7.2.15",
"core-js": "^2.4.1",
"express": "^4.16.2",
"express-basic-auth": "1.2.0",
"nouislider": "^11.1.0",
"rxjs": "^5.5.2",
"tslib": "^1.9.0",
"typescript": "~2.4.2",
"zone.js": "~0.9.1"
},
"devDependencies": {
"#angular-devkit/build-angular": "~0.800.0",
"#angular/cli": "^1.6.3",
"#angular/compiler-cli": "^5.1.3",
"#angular/language-service": "^5.0.0",
"#types/jasmine": "~2.5.53",
"#types/jasminewd2": "~2.0.2",
"#types/jquery": "^3.3.4",
"#types/node": "~6.0.60",
"codelyzer": "^5.0.1",
"enhanced-resolve": "^3.3.0",
"jasmine-core": "~2.6.2",
"jasmine-spec-reporter": "~4.1.0",
"karma": "~1.7.0",
"karma-chrome-launcher": "~2.1.1",
"karma-cli": "~1.0.1",
"karma-coverage-istanbul-reporter": "^1.2.1",
"karma-jasmine": "~1.1.0",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "~5.1.2",
"ts-node": "~3.2.0",
"tslint": "~5.7.0",
"typescript": "~2.4.2"
}
}
and this is my app.module.ts file
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { HttpClientModule } from '#angular/common/http';
import { HttpModule } from '#angular/http';
import { Routes, RouterModule } from '#angular/router';
import { FormsModule } from '#angular/forms';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { ProductsComponent } from './client-page/products/products.component';
import { ClientService } from './client-page/client-offers/client.service';
import { ContractService } from './offer-page/contract.service';
import { FooterComponent } from './footer/footer.component';
import { ClientPageComponent } from './client-page/client-page.component';
import { FirstScreenComponent } from './offer-page/first-screen/first-screen.component';
import { BonusesComponent } from './offer-page/first-screen/bonuses/bonuses.component';
import { DebitCardsComponent } from './offer-page/first-screen/debit-cards/debit-cards.component';
import { ServicesComponent } from './offer-page/first-screen/services/services.component';
import { OfferPageComponent } from './offer-page/offer-page.component';
import { ClientOffersComponent } from './client-page/client-offers/client-offers.component';
import { ProductsService } from './offer-page/first-screen/products.service';
import { ClientPageService } from './client-page/client-page.service';
import { OfferService } from './offer-page/offer.service';
import { RefreshPageService } from './offer-page/first-screen/refresh-page.service';
import { CreateContractComponent } from './create-contract/create-contract.component';
import { AcceptancePageComponent } from './acceptance-page/acceptance-page.component';
import { AttributesComponent } from './offer-page/first-screen/attributes/attributes.component';
import { PricesComponent } from './offer-page/first-screen/prices/prices.component';
import { NamePriceComponent } from './offer-page/first-screen/name-price/name-price.component';
const appRoutes: Routes = [
{ path: '', component: ClientPageComponent },
{ path: 'createContract/:userId/:offerId', component: CreateContractComponent },
{ path: 'offerPage/:contractId', component: OfferPageComponent },
{ path: 'contractCreated/:contractId', component: AcceptancePageComponent }
];
#NgModule({
declarations: [
AppComponent,
HeaderComponent,
ProductsComponent,
FooterComponent,
ClientPageComponent,
FirstScreenComponent,
BonusesComponent,
DebitCardsComponent,
ServicesComponent,
OfferPageComponent,
ClientOffersComponent,
CreateContractComponent,
AcceptancePageComponent,
AttributesComponent,
PricesComponent,
NamePriceComponent
],
imports: [
BrowserModule,
HttpModule,
HttpClientModule,
RouterModule.forRoot(appRoutes),
FormsModule
],
providers: [ ClientService, ContractService,
ProductsService, ClientPageService, OfferService,
RefreshPageService],
bootstrap: [AppComponent]
})
export class AppModule { }
Well after check a lot of commits I found the problem. I miss this line in this file
src/polyfills.ts
import 'core-js/es7/reflect';
Description why it is needed:
Evergreen browsers require these. Used for reflect-metadata in JIT.
But don`t know, what does it do but it works!

Error while rendering the page with the help of Angular 5

I'm doing a project with the help of Angular 5. I am calling an API in it.
I am getting following error:
Error: StaticInjectorError(AppModule)[Router -> ApplicationRef]:
StaticInjectorError(Platform: core)[Router -> ApplicationRef]:
NullInjectorError: No provider for ApplicationRef!
at NullInjector.push../node_modules/#angular/core/fesm5/core.js.NullInjector.get (core.js:951)
at resolveToken (core.js:1195)
at tryResolveToken (core.js:1140)
at StaticInjector.push../node_modules/#angular/core/fesm5/core.js.StaticInjector.get (core.js:1035)
at resolveToken (core.js:1195)
at tryResolveToken (core.js:1140)
at StaticInjector.push../node_modules/#angular/core/fesm5/core.js.StaticInjector.get (core.js:1035)
at resolveNgModuleDep (core.js:8071)
at _callFactory (core.js:8143)
at _createProviderInstance$1 (core.js:8091)
My Package.json is:
{
"name": "demo-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": "^6.0.3",
"#angular/common": "^6.0.3",
"#angular/compiler": "^6.0.3",
"#angular/core": "^6.0.3",
"#angular/forms": "^6.0.3",
"#angular/http": "^6.0.3",
"#angular/platform-browser": "^6.0.3",
"#angular/platform-browser-dynamic": "^6.0.3",
"#angular/router": "^6.0.3",
"core-js": "^2.5.4",
"rxjs": "^6.0.0",
"zone.js": "^0.8.26"
},
"devDependencies": {
"#angular/compiler-cli": "^6.0.3",
"#angular-devkit/build-angular": "~0.6.8",
"typescript": "~2.7.2",
"#angular/cli": "~6.0.8",
"#angular/language-service": "^6.0.3",
"#types/jasmine": "~2.8.6",
"#types/jasminewd2": "~2.0.3",
"#types/node": "~8.9.4",
"codelyzer": "~4.2.1",
"jasmine-core": "~2.99.1",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~1.7.1",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "~2.0.0",
"karma-jasmine": "~1.1.1",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "~5.3.0",
"ts-node": "~5.0.1",
"tslint": "~5.9.1"
}
}
I have app.module.ts as follows, in which I am giving a route "fetch" and calling the corresponding controller.
import { NgModule } from '#angular/core';
import { FetchApiComponent } from './fetch-api/fetch-api.component';
import { Routes, RouterModule } from '#angular/router';
const routes: Routes = [
{ path: 'fetch', component: FetchApiComponent },
];
#NgModule({
declarations: [
FetchApiComponent
],
imports: [
RouterModule.forRoot(routes)
],
exports: [
RouterModule
],
providers: [],
bootstrap: []
})
export class AppModule { }
The main.ts is following
import { enableProdMode } from '#angular/core';
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
if (environment.production) {
enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.log(err));
It is showing that the error is thrown by main.ts file because of the following code.
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.log(err));
Screenshot of the error:
To achieve expected result without eror, import BrowserModule
import { NgModule } from '#angular/core';
import { FetchApiComponent } from './fetch-api/fetch-api.component';
import { Routes, RouterModule } from '#angular/router';
import { BrowserModule } from '#angular/platform-browser';
const routes: Routes = [
{ path: 'fetch', component: FetchApiComponent },
];
#NgModule({
declarations: [
FetchApiComponent
],
imports: [
BrowserModule,
RouterModule.forRoot(routes)
],
exports: [
RouterModule
],
providers: [],
bootstrap: []
})
export class AppModule { }
code sample for reference - https://stackblitz.com/edit/angular-2xbbzj?file=src/app/app.module.ts
Note: Remove BrowserModule from imports to see the same error

app.js:5Uncaught [DEFAULT]: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app)

please how can i solve this? Uncaught [DEFAULT]: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app).V.hasOwnProperty.Object.defineProperty.value # polyfills.js:3e # app.js:5t.ErrorFactory.o.value # app.js:5o # app.js:5e # app.js:5u # app.js:5(anonymous function) # app.component.ts:11__webpack_require__ # bootstrap ec8f9a1…:47(anonymous function) # src async:38__webpack_require__ # bootstrap ec8f9a1…:47(anonymous function) # setImmediate.js:186__webpack_require__ # bootstrap ec8f9a1…:47(anonymous function) # bootstrap ec8f9a1…:139(anonymous function) # bootstrap ec8f9a1…:139
ion-dev.js?v=1.3.7:138 WebSocket is already in CLOSING or CLOSED state.window.IonicDevServer.drainMessageQueue # ion-dev.js?v=1.3.7:138window.IonicDevServer.queueMessageSend # ion-dev.js?v=1.3.7:130window.IonicDevServer.handleError # ion-dev.js?v=1.3.7:61window.onerror # ion-dev.js?v=1.3.7:41
polyfills.js:3 Uncaught TypeError: Illegal invocation enter image description here
package.json
{
"name": "MyEventManager",
"version": "0.0.1",
"author": "Ionic Framework",
"homepage": "http://ionicframework.com/",
"private": true,
"scripts": {
"clean": "ionic-app-scripts clean",
"build": "ionic-app-scripts build",
"lint": "ionic-app-scripts lint",
"ionic:build": "ionic-app-scripts build",
"ionic:serve": "ionic-app-scripts serve"
},
"dependencies": {
"#angular/common": "4.0.2",
"#angular/compiler": "4.0.2",
"#angular/compiler-cli": "4.0.2",
"#angular/core": "4.0.2",
"#angular/forms": "4.0.2",
"#angular/http": "4.0.2",
"#angular/platform-browser": "4.0.2",
"#angular/platform-browser-dynamic": "4.0.2",
"#ionic-native/camera": "^3.6.1",
"#ionic-native/core": "3.6.1",
"#ionic-native/splash-screen": "3.6.1",
"#ionic-native/status-bar": "3.6.1",
"#ionic/storage": "2.0.1",
"cordova-plugin-camera": "^2.4.1",
"firebase": "^3.9.0",
"ionic-angular": "3.1.1",
"ionicons": "3.0.0",
"rxjs": "5.1.1",
"sw-toolbox": "3.4.0",
"zone.js": "^0.8.10"
},
"devDependencies": {
"#ionic/app-scripts": "1.3.7",
"#ionic/cli-plugin-cordova": "1.0.0-rc.2",
"#ionic/cli-plugin-ionic-angular": "1.0.0-rc.2",
"typescript": "~2.2.1"
},
"description": "An Ionic project",
"cordova": {
"plugins": {
"cordova-plugin-camera": {}
}
}
}
app.component.ts
import { Component, NgZone } from '#angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import firebase from 'firebase';
import { HomePage } from '../pages/home/home';
#Component({
templateUrl: 'app.html'
})
export class MyApp {
rootPage:any;
zone:NgZone;
constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen, zone:NgZone) {
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
statusBar.styleDefault();
splashScreen.hide();
});
firebase.initializeApp({
apiKey: "AIzaSyCWRv_TtIrZItQTqPTXR1Rm5QQYy7NNE8c",
authDomain: "geoentreprise.firebaseapp.com",
databaseURL: "https://geoentreprise.firebaseio.com",
storageBucket: "geoentreprise.appspot.com",
messagingSenderId: "653212172629"
});
//initialize the default app
/* var defaultApp = admin.initializeApp(defaultAppConfig);
console.log(defaultApp.name);
//retrieve services via the defaultApp variable...
var defaultAuth=defaultAuth.auth();
var defaultDatabase = defaultApp.database();
//or use the equivalent shorthand notation
defaultAuth = admin.auth();
defaultDatabase = admin.dabase();*/
this.zone = new NgZone({});
}
}
const unsubscribe = firebase.auth().onAuthStateChanged((user) => {
this.zone.run( () => {
if (!user) {
this.rootPage = 'login';
unsubscribe();
} else {
this.rootPage = HomePage;
unsubscribe();
}
});
});
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { ErrorHandler, NgModule } from '#angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '#ionic-native/splash-screen';
import { StatusBar } from '#ionic-native/status-bar';
import { Camera } from '#ionic-native/camera';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { AuthProvider } from '../providers/auth/auth';
import { EventProvider } from '../providers/event/event';
import { ProfileProvider } from '../providers/profile/profile';
class CameraMock {
getPicture(options){
return new Promise( (resolve, reject) => {
resolve(`TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=`);
});
}
}
#NgModule({
declarations: [
MyApp,
HomePage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
AuthProvider,
EventProvider,
ProfileProvider,
{provide: Camera, useClass: CameraMock}
]
})
export class AppModule {}

Angular2: Web Speech API - Voice recognition

After reading the documentation of webkitSpeechRecognition (voice recognition in Javascript) I tried to implement it in Angular 2.
But when I did this:
const recognition = new webkitSpeechRecognition();
TypeScript say this error:
[ts] Cannot find name 'webkitSpeechRecognition'. any
And if I try to extract webkitSpeechRecognition from window:
if ('webkitSpeechRecognition' in window) {
console.log("Enters inside the condition"); // => It's printing
const { webkitSpeechRecognition } = window; // => TypeScript Error
const recognition = new webkitSpeechRecognition();
}
If I comment the last two lines the console.log is printed, enters to the condition! webkitSpeechRecognition exists inside window!! But if not comment the last two lines the TypeScript error now is this:
[ts] Type 'Window' has no property 'webkitSpeechRecognition' and no string index signature.
const webkitSpeechRecognition: any
How can I create a new recognition in Angular 2? Has anybody tried it?
Finally I solved creating an interface!!
export interface IWindow extends Window {
webkitSpeechRecognition: any;
}
And:
const {webkitSpeechRecognition} : IWindow = <IWindow>window;
const recognition = new webkitSpeechRecognition();
In Angular 9, it worked me but using const speechRecognition = window['webkitSpeechRecognition'];
note that the window 'w' is lowercase.
home.component.html
<select (change)="onChangeEvent($event)"><option>Chartdata</option><option>Tabledata</option></select>
<div id="chart" (click)="voice()">ChartData</div>
<div id="table">TableData</div>
<input type="text" placeholder="Speak out"/>
<p>RxCompoent.message: {{message}}</p>
<p><input type="text" value="{{message}}"></p>
<button
[disabled]="service.started$ | async"
(click)="listen()"
>listen</button>
<p>lang: ja</p>
<p>grammars: none</p>
home.component.ts
import { Component, OnInit } from '#angular/core';
import { FormBuilder, FormGroup, Validators } from '#angular/forms';
import Speech from 'speak-tts';
import { RxSpeechRecognitionService, resultList, } from '#kamiazya/ngx-speech-recognition';
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css'],
providers: [ RxSpeechRecognitionService ]
})
export class HomeComponent implements OnInit {
data:any;
nestedjson:any;
message = '';
constructor(private formBuilder: FormBuilder,public service: RxSpeechRecognitionService) {
}
ngOnInit() {
// this.voicex();
}
listen() {
this.service
.listen()
.pipe(resultList)
.subscribe((list: SpeechRecognitionResultList) => {
this.message = list.item(0).item(0).transcript;
console.log('RxComponent:onresult', this.message, list);
});
}
voice(){
this.voicex();
}
voicex(){
const ut = new SpeechSynthesisUtterance('Speak out');
speechSynthesis.speak(ut);
}
onChangeEvent(ev) {
console.log(ev.target.value); // should print option1
}
}
app.module
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { UsermanagementComponent } from './usermanagement/usermanagement.component';
import { HomeComponent } from './home/home.component';
import { HeaderComponent } from './shared/header/header.component';
import { LoginComponent } from './login/login.component';
import {HttpModule} from '#angular/http';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { ChartModule,HIGHCHARTS_MODULES } from 'angular-highcharts';
import * as exporting from 'highcharts/modules/exporting.src';
import * as exportdata from 'highcharts/modules/export-data.src';
import {SpeechRecognitionModule} from '#kamiazya/ngx-speech-recognition';
#NgModule({
declarations: [
AppComponent,
UsermanagementComponent,
HomeComponent,
HeaderComponent,
LoginComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
ReactiveFormsModule,
HttpModule,
ChartModule,
SpeechRecognitionModule.withConfig({ lang: 'en-US', interimResults: true, maxAlternatives: 10, })
],
providers: [{provide:HIGHCHARTS_MODULES,useFactory:() =>[exporting,exportdata]}],
bootstrap: [AppComponent]
})
export class AppModule { }
package.json
{
"name": "sampleproject",
"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": "~8.2.8",
"#angular/common": "~8.2.8",
"#angular/compiler": "~8.2.8",
"#angular/core": "~8.2.8",
"#angular/forms": "~8.2.8",
"#angular/http": "^7.2.15",
"#angular/platform-browser": "~8.2.8",
"#angular/platform-browser-dynamic": "~8.2.8",
"#angular/router": "~8.2.8",
"#kamiazya/ngx-speech-recognition": "^0.4.3",
"angular-highcharts": "^8.0.3",
"highcharts": "^7.2.0",
"jquery": "^3.4.1",
"rxjs": "~6.4.0",
"rxjs-compat": "^6.5.3",
"speak-tts": "^2.0.8",
"tslib": "^1.10.0",
"zone.js": "~0.9.1"
},
"devDependencies": {
"#angular-devkit/build-angular": "~0.803.6",
"#angular/cli": "~8.3.6",
"#angular/compiler-cli": "~8.2.8",
"#angular/language-service": "~8.2.8",
"#types/node": "~8.9.4",
"#types/jasmine": "~3.3.8",
"#types/jasminewd2": "~2.0.3",
"codelyzer": "^5.0.0",
"jasmine-core": "~3.4.0",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~4.1.0",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "~2.0.1",
"karma-jasmine": "~2.0.1",
"karma-jasmine-html-reporter": "^1.4.0",
"protractor": "~5.4.0",
"ts-node": "~7.0.0",
"tslint": "~5.15.0",
"typescript": "~3.5.3"
}
}
You can solve the problem by
const speechRecognition = Window['webkitSpeechRecognition'];
Or if You are using jQuery
const sr = $(window).get(0).webkitSpeechRecognition;

Categories