Showing posts with label angular 5. Show all posts
Showing posts with label angular 5. Show all posts

Tuesday, February 19, 2019

ERROR TypeError: Cannot create property 'validator' on string 'name'

Hi Guys ,

Today I have faced this error :

 ERROR TypeError: Cannot create property 'validator' on string 'name'



The solution is to add the following line in app.module.ts highlighted in Yellow.



The complete console log is as below:


core.js:3121 Angular is running in the development mode. Call enableProdMode() to enable the production mode.
SignUpComponent.html:1 ERROR TypeError: Cannot create property 'validator' on string 'name'
    at setUpControl (forms.js:1686)
    at FormControlDirective.push../node_modules/@angular/forms/fesm5/forms.js.FormControlDirective.ngOnChanges (forms.js:4373)
    at checkAndUpdateDirectiveInline (core.js:9239)
    at checkAndUpdateNodeInline (core.js:10507)
    at checkAndUpdateNode (core.js:10469)
    at debugCheckAndUpdateNode (core.js:11102)
    at debugCheckDirectivesFn (core.js:11062)
    at Object.eval [as updateDirectives] (SignUpComponent.html:3)
    at Object.debugUpdateDirectives [as updateDirectives] (core.js:11054)
    at checkAndUpdateView (core.js:10451)
View_SignUpComponent_0 @ SignUpComponent.html:1
proxyClass @ compiler.js:10173
push../node_modules/@angular/core/fesm5/core.js.DebugContext_.logError @ core.js:11306
push../node_modules/@angular/core/fesm5/core.js.ErrorHandler.handleError @ core.js:1719
(anonymous) @ core.js:4578
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:391
push../node_modules/zone.js/dist/zone.js.Zone.run @ zone.js:150
push../node_modules/@angular/core/fesm5/core.js.NgZone.runOutsideAngular @ core.js:3779
push../node_modules/@angular/core/fesm5/core.js.ApplicationRef.tick @ core.js:4578
(anonymous) @ core.js:4462
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:391
onInvoke @ core.js:3820
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:390
push../node_modules/zone.js/dist/zone.js.Zone.run @ zone.js:150
push../node_modules/@angular/core/fesm5/core.js.NgZone.run @ core.js:3734
next @ core.js:4462
schedulerFn @ core.js:3551
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub @ Subscriber.js:196
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next @ Subscriber.js:134
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next @ Subscriber.js:77
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next @ Subscriber.js:54
push../node_modules/rxjs/_esm5/internal/Subject.js.Subject.next @ Subject.js:47
push../node_modules/@angular/core/fesm5/core.js.EventEmitter.emit @ core.js:3535
checkStable @ core.js:3789
onHasTask @ core.js:3833
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.hasTask @ zone.js:443
push../node_modules/zone.js/dist/zone.js.ZoneDelegate._updateTaskCount @ zone.js:463
push../node_modules/zone.js/dist/zone.js.Zone._updateTaskCount @ zone.js:291
push../node_modules/zone.js/dist/zone.js.Zone.runTask @ zone.js:212
drainMicroTaskQueue @ zone.js:601
Promise.then (async)
scheduleMicroTask @ zone.js:584
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask @ zone.js:413
push../node_modules/zone.js/dist/zone.js.Zone.scheduleTask @ zone.js:238
push../node_modules/zone.js/dist/zone.js.Zone.scheduleMicroTask @ zone.js:258
scheduleResolveOrReject @ zone.js:879
ZoneAwarePromise.then @ zone.js:1012
push../node_modules/@angular/core/fesm5/core.js.PlatformRef.bootstrapModule @ core.js:4345
./src/main.ts @ main.ts:11
__webpack_require__ @ bootstrap:76
0 @ main.ts:12
__webpack_require__ @ bootstrap:76
checkDeferredModules @ bootstrap:43
webpackJsonpCallback @ bootstrap:30
(anonymous) @ main.js:1
SignUpComponent.html:1 ERROR CONTEXT DebugContext_ {view: {…}, nodeIndex: 2, nodeDef: {…}, elDef: {…}, elView: {…}}
View_SignUpComponent_0 @ SignUpComponent.html:1
proxyClass @ compiler.js:10173
push../node_modules/@angular/core/fesm5/core.js.DebugContext_.logError @ core.js:11306
push../node_modules/@angular/core/fesm5/core.js.ErrorHandler.handleError @ core.js:1724
(anonymous) @ core.js:4578
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:391
push../node_modules/zone.js/dist/zone.js.Zone.run @ zone.js:150
push../node_modules/@angular/core/fesm5/core.js.NgZone.runOutsideAngular @ core.js:3779
push../node_modules/@angular/core/fesm5/core.js.ApplicationRef.tick @ core.js:4578
(anonymous) @ core.js:4462
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:391
onInvoke @ core.js:3820
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:390
push../node_modules/zone.js/dist/zone.js.Zone.run @ zone.js:150
push../node_modules/@angular/core/fesm5/core.js.NgZone.run @ core.js:3734
next @ core.js:4462
schedulerFn @ core.js:3551
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub @ Subscriber.js:196
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next @ Subscriber.js:134
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next @ Subscriber.js:77
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next @ Subscriber.js:54
push../node_modules/rxjs/_esm5/internal/Subject.js.Subject.next @ Subject.js:47
push../node_modules/@angular/core/fesm5/core.js.EventEmitter.emit @ core.js:3535
checkStable @ core.js:3789
onHasTask @ core.js:3833
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.hasTask @ zone.js:443
push../node_modules/zone.js/dist/zone.js.ZoneDelegate._updateTaskCount @ zone.js:463
push../node_modules/zone.js/dist/zone.js.Zone._updateTaskCount @ zone.js:291
push../node_modules/zone.js/dist/zone.js.Zone.runTask @ zone.js:212
drainMicroTaskQueue @ zone.js:601
Promise.then (async)
scheduleMicroTask @ zone.js:584
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask @ zone.js:413
push../node_modules/zone.js/dist/zone.js.Zone.scheduleTask @ zone.js:238
push../node_modules/zone.js/dist/zone.js.Zone.scheduleMicroTask @ zone.js:258
scheduleResolveOrReject @ zone.js:879
ZoneAwarePromise.then @ zone.js:1012
push../node_modules/@angular/core/fesm5/core.js.PlatformRef.bootstrapModule @ core.js:4345
./src/main.ts @ main.ts:11
__webpack_require__ @ bootstrap:76
0 @ main.ts:12
__webpack_require__ @ bootstrap:76
checkDeferredModules @ bootstrap:43
webpackJsonpCallback @ bootstrap:30
(anonymous) @ main.js:1

ERROR Error: Uncaught (in promise): ReferenceError: Validators is not defined

Hi Guys ,

Today I have faced this error :

ERROR Error: Uncaught (in promise): ReferenceError: Validators is not defined

When I check the command prompt the error is like this :
-----ng serve--------------------------------------------------------------------------------------------------------------

ERROR in src/app/sign-up/sign-up.component.ts(17,27): error TS2304: Cannot find name 'Validators'.
src/app/sign-up/sign-up.component.ts(17,48): error TS2304: Cannot find name 'Validators'.
src/app/sign-up/sign-up.component.ts(17,73): error TS2304: Cannot find name 'Validators'.
-----------------------------------------------------------------------------------------------------------------------

The solution is to add the following line in your component.ts file, highlighted in Yellow.

import { Validators } from '@angular/forms';


The complete console log is as below:


ERROR Error: Uncaught (in promise): ReferenceError: Validators is not defined
ReferenceError: Validators is not defined
    at new SignUpComponent (sign-up.component.ts:17)
    at createClass (core.js:9292)
    at createDirectiveInstance (core.js:9179)
    at createViewNodes (core.js:10399)
    at createRootView (core.js:10313)
    at callWithDebugContext (core.js:11344)
    at Object.debugCreateRootView [as createRootView] (core.js:10831)
    at ComponentFactory_.push../node_modules/@angular/core/fesm5/core.js.ComponentFactory_.create (core.js:8659)
    at ComponentFactoryBoundToModule.push../node_modules/@angular/core/fesm5/core.js.ComponentFactoryBoundToModule.create (core.js:3311)
    at ViewContainerRef_.push../node_modules/@angular/core/fesm5/core.js.ViewContainerRef_.createComponent (core.js:8769)
    at resolvePromise (zone.js:831)
    at resolvePromise (zone.js:788)
    at zone.js:892
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
    at Object.onInvokeTask (core.js:3811)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:422)
    at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:195)
    at drainMicroTaskQueue (zone.js:601)
defaultErrorLogger @ core.js:1673
localhost/:1 Unchecked runtime.lastError: The message port closed before a response was received.
core.js:1673 ERROR Error: Uncaught (in promise): ReferenceError: Validators is not defined
ReferenceError: Validators is not defined
    at new SignUpComponent (sign-up.component.ts:17)
    at createClass (core.js:9292)
    at createDirectiveInstance (core.js:9179)
    at createViewNodes (core.js:10399)
    at createRootView (core.js:10313)
    at callWithDebugContext (core.js:11344)
    at Object.debugCreateRootView [as createRootView] (core.js:10831)
    at ComponentFactory_.push../node_modules/@angular/core/fesm5/core.js.ComponentFactory_.create (core.js:8659)
    at ComponentFactoryBoundToModule.push../node_modules/@angular/core/fesm5/core.js.ComponentFactoryBoundToModule.create (core.js:3311)
    at ViewContainerRef_.push../node_modules/@angular/core/fesm5/core.js.ViewContainerRef_.createComponent (core.js:8769)
    at resolvePromise (zone.js:831)
    at resolvePromise (zone.js:788)
    at zone.js:892
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
    at Object.onInvokeTask (core.js:3811)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:422)
    at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:195)
    at drainMicroTaskQueue (zone.js:601)
    at ZoneTask.push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (zone.js:502)
    at invokeTask (zone.js:1744)
defaultErrorLogger @ core.js:1673

Uncaught Error: Template parse errors:'router-outlet' is not a known element:

Hi Guys ,

Today I have faced this error :

Uncaught Error: Template parse errors:'router-outlet' is not a known element:


The solution is to add the following line in app.module.ts highlighted in Yellow.

@NgModule({
imports: [
    BrowserModule,
    RouterModule.forRoot(appRoutes),
    FormsModule             
],


The complete console log is as below:

Uncaught Error: 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.
2. If 'router-outlet' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("
   <a routerLink= "/explore"> Explore </a>
 </nav>
 [ERROR ->]<router-outlet></router-outlet>
<form #form="ngForm" (ngSubmit)="onSubmit(form.value)">
 <label>Name:"): ng:///AppModule/AppComponent.html@5:1
    at syntaxError (compiler.js:1021)
    at TemplateParser.push../node_modules/@angular/compiler/fesm5/compiler.js.TemplateParser.parse (compiler.js:14830)
    at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._parseTemplate (compiler.js:24018)
    at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._compileTemplate (compiler.js:24005)
    at compiler.js:23948
    at Set.forEach (<anonymous>)
    at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._compileComponents (compiler.js:23948)
    at compiler.js:23858
    at Object.then (compiler.js:1012)
    at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._compileModuleAndComponents (compiler.js:23857)

Saturday, February 16, 2019

This project uses version 5.5.12 of RxJs, which is not supported by Angular v6.

Hi Guys,

You will face this error if you use angular 6.

This project uses version 5.5.12 of RxJs, which is not supported by Angular v6.

The solution is to change the version of rxjs in package.json

-----------package.json-----------------------------------

 "rxjs": "6.3.3"

---------------------------------------------------

Can't bind to 'ngModel' since it isn't a known property of 'input'

Hey Guys ,

Today let's look at the following error :

'Can't bind to 'ngModel' since it isn't a known property of 'input"

This will come in case of two way binding.

The fix is simple , you need to import the forms module to your app module.

-----------app.module----------------------------

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
-----------------------------------------------------------------------------

Import the two lines highlighted above and it should work fine .

View full source at here

Cannot assign to 'name' because it is a constant or a read-only property.

Hi Guys,

I have faced an error like "Cannot assign to 'name' because it is a constant or a read-only property." .

The code is as below

------------app.component.ts-----------------------------------
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html' //// refer app.component.html for property binding
})
export class AppComponent {
  name="";

  testEventBind(userName: string) {
      name=userName;
  }
}
------------------------------------------------------------


I have highlighted the line which causes this error.

All you have to do is to use this keyword , change the highlighted line as below,

this.name=userName;


This should fix the issue.

Monday, February 4, 2019

ERROR in node_modules/rxjs/internal/types.d.ts(81,44): error TS1005: ';' expected.

Hey Guys ,

I have faced this issue on serving a newly created project using angular cli.
ERROR in node_modules/rxjs/internal/types.d.ts(81,44): error TS1005: ';' expected.
node_modules/rxjs/internal/types.d.ts(81,74): error TS1005: ';' expected.
node_modules/rxjs/internal/types.d.ts(81,77): error TS1109: Expression expected.

Solution 1:
Remove the ^ symbol from package.json from
  "rxjs": "^6.0.0",


execute :
npm update

it should work fine.If this doesn't work try this:

Solution 2:
In package.json set the version of rxjs as below:
 "rxjs": "6.3.3",


execute :
npm update

it should work.A working version is here click

Friday, June 22, 2018

Error: Cannot find module '@angular-devkit/core'

Hi Guys, You might have faced this error "Error: Cannot find module '@angular-devkit/core'" while calling the command "ng serve". The full stack trace is as below .





module.js:487
    throw err;
    ^

Error: Cannot find module '@angular-devkit/core'
    at Function.Module._resolveFilename (module.js:485:15)
    at Function.Module._load (module.js:437:25)
    at Module.require (module.js:513:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (F:\shahbaz\study\angular4\projects\my-fifth-app\test5\node_modules\@angular-devkit\schematics\src\tree\virtual.js:10:16)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)


To fix just change the following property in package.json
"@angular/cli": "1.6.0",
to
"@angular/cli": "^1.6.0",

Once done run npm update

This should solve the problem.


The "@angular/compiler-cli" package was not properly installed.


Hi Guys, You might have faced this error "The "@angular/compiler-cli" package was not properly installed. Error: Error: Cannot find module '@angular/compiler-cli'" while calling the command "ng serve". The full stack trace is as below


The "@angular/compiler-cli" package was not properly installed. Error: Error: Cannot find module '@angular/compiler-cli'
Error: The "@angular/compiler-cli" package was not properly installed. Error: Error: Cannot find module '@angular/compiler-cli'
    at Object.CompilerCliIsSupported (C:\Users\user\AppData\Roaming\npm\node_modules\@angular\cli\node_modules\@ngtools\webpack\src\ngtools_api.js:25:15)
    at new AotPlugin (C:\Users\user\AppData\Roaming\npm\node_modules\@angular\cli\node_modules\@ngtools\webpack\src\plugin.js:29:23)
    at _createAotPlugin (C:\Users\user\AppData\Roaming\npm\node_modules\@angular\cli\models\webpack-configs\typescript.js:92:16)
    at Object.getNonAotConfig (C:\Users\user\AppData\Roaming\npm\node_modules\@angular\cli\models\webpack-configs\typescript.js:100:19)
    at NgCliWebpackConfig.buildConfig (C:\Users\user\AppData\Roaming\npm\node_modules\@angular\cli\models\webpack-config.js:33:37)
    at Class.run (C:\Users\user\AppData\Roaming\npm\node_modules\@angular\cli\tasks\serve.js:71:98)
    at check_port_1.checkPort.then.port (C:\Users\user\AppData\Roaming\npm\node_modules\@angular\cli\commands\serve.js:123:26)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:169:7)

It can due to various reasons ,
1. Your node_modules folder is not having the required modules .
Check the node_modules folder and see if it has all the modules. If the modules are missing just do npm install
2. If the modules are available check the version of typescript , nodejs and angular cli.
3. If nothing works create a new project using ng new project-name and replace the src directory.

Friday, June 8, 2018

ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment:

Hi Guys,

This blog is about issues I have faced while creating a route in Angular 5.

When I try to hit a url "http://localhost:4200/home", I faced the following error.




Error: Cannot match any routes. URL Segment: 'home'
    at ApplyRedirects.noMatchError (router.js:1719)
    at CatchSubscriber.eval [as selector] (router.js:1684)
    at CatchSubscriber.error (catchError.js:105)
    at MapSubscriber.Subscriber._error (Subscriber.js:131)
    at MapSubscriber.Subscriber.error (Subscriber.js:105)
    at MapSubscriber.Subscriber._error (Subscriber.js:131)
    at MapSubscriber.Subscriber.error (Subscriber.js:105)
    at MapSubscriber.Subscriber._error (Subscriber.js:131)
    at MapSubscriber.Subscriber.error (Subscriber.js:105)
    at LastSubscriber.Subscriber._error (Subscriber.js:131)
    at ApplyRedirects.noMatchError (router.js:1719)
    at CatchSubscriber.eval [as selector] (router.js:1684)
    at CatchSubscriber.error (catchError.js:105)
    at MapSubscriber.Subscriber._error (Subscriber.js:131)
    at MapSubscriber.Subscriber.error (Subscriber.js:105)
    at MapSubscriber.Subscriber._error (Subscriber.js:131)
    at MapSubscriber.Subscriber.error (Subscriber.js:105)
    at MapSubscriber.Subscriber._error (Subscriber.js:131)
    at MapSubscriber.Subscriber.error (Subscriber.js:105)
    at LastSubscriber.Subscriber._error (Subscriber.js:131)
    at resolvePromise (zone.js:821)
    at resolvePromise (zone.js:785)
    at eval (zone.js:870)
    at ZoneDelegate.invokeTask (zone.js:421)
    at Object.onInvokeTask (core.js:4744)
    at ZoneDelegate.invokeTask (zone.js:420)
    at Zone.runTask (zone.js:188)
    at drainMicroTaskQueue (zone.js:594)

The fix is pretty simple .When I added the following line in app.module.ts file , it worked.

const appRoutes:Routes =[
{path:'home',component: HomeComponent}
];

If you are facing the same error even after adding this piece of  code then check if you have added a slash in the path {path :'\home' . Remove the slash if you have added it.

view the full source in Git

Saturday, May 26, 2018

has been blocked by CORS policy: No 'Access-Control-Allow-Origin'

Hi Guys,

This blog is about issues I have faced while fetching data from a REST Web Service.

When I try to get the data from the service I faced an error like ,

Failed to load http://localhost:8090/org.myProject/question: Redirect from 'http://localhost:8090/org.myProject/question' to 'http://localhost:8090/org.myProject/question/' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
This is because the rest service does not provide the response for Http requests from a different domain . The solution to this is add some extra the configuration in the Service to accept requests from a different domains. Lets have a look at the code.
import { EventEmitter, Injectable } from '@angular/core';
import { Headers, Http ,Response} from '@angular/http';
import {  HttpClientModule } from '@angular/common/http';
import {  HttpModule } from '@angular/http';


import 'rxjs/Rx';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class QuestionService{
constructor(private http:Http) {}
loadQuestions(){


return this.http.get('http://localhost:8090/org.myProject/question')
.map(
        (response: Response) => {
          const data = response.json();
       
          return data;
        }
      )
      .catch(
        (error: Response) => {
          return Observable.throw('Something went wrong');
        }
      );

}
}
That's the service,check out the  controller .
import { Component, OnInit } from '@angular/core';
import { QuestionService } from './question.service';


@Component({
  selector: 'app-question',
  templateUrl: './question.component.html',
  styleUrls: ['./question.component.css'],
  providers:[QuestionService]
})
export class QuestionComponent  {

  constructor(private questionService:QuestionService) { }




onGet() {

  this.questionService.loadQuestions().subscribe(
        (questions: any[]) => {this.questions = questions;console.log(questions);},
        (error) => console.log(error)
      );

  }

  var questions;
}

The component file is as below

<div class="container">
<div class="row">
<div>
Question:
<select id="question"  >
<option>Select</option>
<option *ngFor="let question of questions" ngValue="question">{{question.subjectDesc}}</option>
</select>
</div>
</div>
<div class="row">
<div>
 <button class="btn btn-primary" (click)="onGet()">Get Server Response </button>
</div>
</div>

</div>

The change actually has to be done on the server side code . I am using a Spring Web application at the back end . By default it does not respond other hosts. So , Lets add the following entries to web.xml .
<filter>
<filter-name>CORS</filter-name>
<filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
</filter>
<filter-mapping>
        <filter-name>CORS</filter-name>
        <url-pattern>/*</url-pattern>
</filter-mapping>

Test once the service is deployed.

Sunday, January 14, 2018

StaticInjectorError NullInjectorError: No provider for MyService


Hi Guys,

You might have faced an error like "StaticInjectorError NullInjectorError: No provider for MyService".

This error comes when you try to create a service and something goes wrong.

Let's see the full stack trace.

ERROR Error: StaticInjectorError[MyService]: 
  StaticInjectorError[MyService]: 
    NullInjectorError: No provider for MyService!
    at _NullInjector.get (webpack-internal:///../../../core/esm5/core.js:1189)
    at resolveToken (webpack-internal:///../../../core/esm5/core.js:1477)
    at tryResolveToken (webpack-internal:///../../../core/esm5/core.js:1419)
    at StaticInjector.get (webpack-internal:///../../../core/esm5/core.js:1290)
    at resolveToken (webpack-internal:///../../../core/esm5/core.js:1477)
    at tryResolveToken (webpack-internal:///../../../core/esm5/core.js:1419)
    at StaticInjector.get (webpack-internal:///../../../core/esm5/core.js:1290)
    at resolveNgModuleDep (webpack-internal:///../../../core/esm5/core.js:11074)
    at NgModuleRef_.get (webpack-internal:///../../../core/esm5/core.js:12306)
    at resolveDep (webpack-internal:///../../../core/esm5/core.js:12804)


I have few tips which will help you Debug this.


Let's see the working code
import { Component, OnInit } from '@angular/core';
import { MyService } from './myapp.service';


@Component({
  selector: 'app-question',
  templateUrl: './myapp.component.html',
  styleUrls: ['./myapp.component.css'],
  providers:[MyService ]
})
export class MyComponent implements OnInit {

  constructor(private myService:MyService ) { }
  //constructor() { }
  ngOnInit() {

this.data=this.myService.loadData();
console.log(data);
  }
var data={};

}
In the above code I have successfully created a service .You need to check if you have specified the service in providers.If you have not added ,add it in the provider attribute of @Component decorator .

Apart from this you need to add the service to app.module.ts


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { MyService } from './myapp.service';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [MyService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Friday, December 29, 2017

Uncaught Error: Encountered undefined provider

Hi Guys,

Here is how you can fix the issue "Uncaught Error: Encountered undefined provider" . Have a look at the stack trace below.


compiler.js:485 

Uncaught Error: Encountered undefined provider! Usually this means you have a circular dependencies (might be caused by using 'barrel' index.ts files.
    at syntaxError (compiler.js:485)
    at eval (compiler.js:15725)
    at Array.forEach (<anonymous>)
    at CompileMetadataResolver._getProvidersMetadata (compiler.js:15710)
    at CompileMetadataResolver.getNonNormalizedDirectiveMetadata (compiler.js:14994)
    at CompileMetadataResolver._getEntryComponentMetadata (compiler.js:15812)
    at eval (compiler.js:15293)
    at Array.map (<anonymous>)
    at CompileMetadataResolver.getNgModuleMetadata (compiler.js:15293)
    at JitCompiler._loadModules (compiler.js:34226)


To find out which part of the code is throwing  this error , first have a check in the component.ts file.
Check the value of provider attribute in the @Component decorator .



Wednesday, December 6, 2017

node_modules appears empty, you may need to run 'npm install'

Hi Guys,


You might face the error node_modules appears empty, you may need to run 'npm install'  if you try to test an angular 2/4/5 application . 

node_modules appears empty, you may need to run 'npm install'
This error occurs when you use the command ng serve.
C:\projects\my-app> ng serve
Note that this command is used to start a server , serving the angular application .

The most common cause of this error is missing node_modules folder in the directory from which you have called ng serve.

To solve this take the following steps.

1. Check , if you have called ng serve from the correct location ? to serve the application you need to navigate to the project folder and then call ng serve .

2. If you are in correct folder , check if you have a folder named node_modules in it.If not your project is incomplete . Create a new application using ng new and replace the src folder of new app with src folder of your existing app.

C:\projects> ng new my-app-new
Copy the src folder in my-app to my-app-new
C:\projects> cd my-app-new
C:\projects\my-app-new> ng serve
3. If you have node_modules  folder available and in your app folder then it might be corrupted. To solve this create a new application using ng new and replace the src folder of new app with src folder of your existing app.


Important links
S O

Friday, November 24, 2017

The selector "app-root" did not match any elements

Hi Guys,

You might face this error when we try add a newly created component in Angular 2/4/5.

Let's have a look at the complete stack trace:


ERROR Error: The selector "app-root" did not match any elements
    at DefaultDomRenderer2.selectRootElement (platform-browser.js:2791)
    at DebugRenderer2.selectRootElement (core.js:14962)
    at createElement (core.js:10279)
    at createViewNodes (core.js:13409)
    at createRootView (core.js:13338)
    at callWithDebugContext (core.js:14739)
    at Object.debugCreateRootView [as createRootView] (core.js:14040)
    at ComponentFactory_.create (core.js:10959)
    at ComponentFactoryBoundToModule.create (core.js:3919)
    at ApplicationRef.bootstrap (core.js:5730)
This would come if you have placed the newly created component selector in the root component .

Let's look at the working code:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>MyFirstApp</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>

</body>
</html>

Remember this code is working fine , now lets see the erroneous code.
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>MyFirstApp</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-mycomponent></app-mycomponent>
</body>
</html>

So the error is due to the app-mycomponent which is not present. So , how to fix this error ? You need to add the new component in the app component , not in the index.html.
<app-mycomponent></app-mycomponent>
<div style="text-align:center">
  <h1>
    Welcome  {{title}}!
  </h1>
  <img width="300" src="xyz">
</div>
Now, we see the output as:
mycomponent works!

Refer to similar answers in Stack Overflow site.

ec2-user@ec2 Permission denied