I am new to Angular 2. As for now I am trying to fetch user data from Github API. I have one component (user.component) and here is its code:
import {Component} from '#angular/core';
import {userService} from './user.service';
import'rxjs/add/operator/map';
#Component({
selector: 'users',
template: `
<h2>Users</h2>
`,
providers: [userService]
})
export class UserComponent{
constructor(private _userService: userService)
{
this._userService.getUser().subscribe( user => {console.log(user)})
}
}
The code of user.Service.ts:
import {Injectable} from '#angular/core'
import {Http, Headers} from '#angular/http'
import'rxjs/add/operator/map';
#Injectable()
export class userService{
private username : string;
constructor (private _http:Http){
console.log("Github Service is ready...")
this.username = "example"
}
getUser(){
return this._http.get("http://api.github.com/users/"+example)
.map(res => res.json)
}
}
And this is app.module.ts:
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { UserComponent } from './user.component'
import {HttpModule } from '#angular/http';
import { AppComponent } from './app.component';
#NgModule({
imports: [ BrowserModule, HttpModule ],
declarations: [ AppComponent,UserComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
And finally here is app.component.ts:
import { Component } from '#angular/core';
import { UserService } from './user.service'
#Component({
selector: 'my-app',
template: `<h1>Hello {{name}}</h1><users></users>`,
providers: [CourseService]
})
export class AppComponent { name = 'John'; }
You should add providers: [CourseService] to the module, not the app component.
#NgModule({
imports: [ BrowserModule, HttpModule ],
declarations: [ AppComponent,UserComponent ],
bootstrap: [ AppComponent ],
providers: [ CourseService ]
})
and remove it from the #Component decorator.
Edit: I'm glad you got this working, but the commenter is right - this was not a correct solution, I was mistaken.
example is not a local variable inside getUser()
I think you meant to write is:
getUser(){
return this._http.get("http://api.github.com/users/" + this.username)
.map(res => res.json)
}
Related
I have a simple task I'm trying to accomplish. I've created a SharedModule with a component called InputComponent. I want to use this component in SigninComponent which is part of the AuthModule. I export the InputComponent from SharedModule and import the SharedModule into the AuthModule. However, when I use <app-input>, I get the following error:
src/app/auth/signin/signin.component.html:3:5 - error NG8001: 'app-input' is not a known element:
1. If 'app-input' is an Angular component, then verify that it is part of this module.
shared.module.ts
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { InputComponent } from './input/input.component';
#NgModule({
declarations: [
InputComponent
],
imports: [
CommonModule
],
exports: [
InputComponent
]
})
export class SharedModule { }
input.component.ts
import { Component, OnInit, Input } from '#angular/core';
#Component({
selector: 'app-input',
templateUrl: './input.component.html',
styleUrls: ['./input.component.css']
})
export class InputComponent implements OnInit {
#Input() label?:string;
#Input() inputType?:string;
constructor() { }
ngOnInit(): void {
}
}
auth.module.ts
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { SharedModule } from '../shared/shared.module';
import { SigninComponent } from './signin/signin.component';
import { SignupComponent } from './signup/signup.component';
import { SignoutComponent } from './signout/signout.component';
#NgModule({
declarations: [
SigninComponent,
SignupComponent,
SignoutComponent
],
imports: [
CommonModule,
SharedModule
]
})
export class AuthModule { }
signin.component.html
<h1>Sign In</h1>
<form>
<app-input inputType="email" label="Email Address"></app-input>
</form>
Any help would be greatly appreciated. I feel like I'm missing something small and just can't figure it out.
Extra note
I have other components within the same AuthModule (SignoutComponent for example), that will throw the same error if I try to use <app-signout>
Posting here just incase someone runs into something similar.
Due to how I had routing setup, I was eagerly loading my Auth components. (not lazy loading) In order to get this to work, I needed to import my AuthModule to my AppModule.
I have a simple code of HttpInterceptor, i'm trying to add some data in the request headr, but this is not working.
MyInterceptorService Class Code :
import { Injectable } from '#angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '#angular/common/http';
import { Observable } from 'rxjs';
#Injectable()
export class MyInterceptorService implements HttpInterceptor {
constructor() { }
intercept(req:HttpRequest<any>, next:HttpHandler):Observable<HttpEvent<any>>
{
console.log("hello");
return next.handle(
req.clone({
headers: req.headers.set('Authorization', 'Bearer ')
})
);
}
}
Module Class Code
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import {FormsModule} from '#angular/forms';
import { SecretComponent } from './secret/secret.component';
import { ErreurComponent } from './erreur/erreur.component';
import { HTTP_INTERCEPTORS } from '#angular/common/http';
import { MyInterceptorService } from './my-interceptor.service';
#NgModule({
declarations: [
AppComponent,
SecretComponent,
ErreurComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: MyInterceptorService,
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule { }
The Console message is never displayed and the Http Header is not updated
Are you sure you make an HTTP-request somewhere in your code? For example:
import { Component, OnInit } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
constructor(private http: HttpClient) {}
ngOnInit() {
this.http.get('http://www.google.com')
.subscribe();
}
}
I made a Stackblitz example with copy-paste of your MyInterceptorService and it displays the console 'hello' message: https://stackblitz.com/edit/angular-rhpnjg
I am creating my app project with ionic 4.
In the past, i.e. ionic 3, I can import TranslateModule.forChild() for every page module.ts. But with ionic 4, if two pages get loading TranslateModule.forChild(), it will cause Maximum call stack size exceeded. If I delete one of them, it will works fine without stack size but just that page cannot translate any more.
Actually, my ionic version is 5.4.6.
Here are my codes:
app.module.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { RouteReuseStrategy } from '#angular/router';
import { IonicModule, IonicRouteStrategy } from '#ionic/angular';
import { SplashScreen } from '#ionic-native/splash-screen/ngx';
import { StatusBar } from '#ionic-native/status-bar/ngx';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { TranslateModule, TranslateLoader } from '#ngx-translate/core';
import { TranslateHttpLoader } from '#ngx-translate/http-loader';
import { HttpClientModule, HttpClient } from '#angular/common/http';
export function createTranslateLoader(http: HttpClient) {
return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}
#NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [
BrowserModule,
IonicModule.forRoot(),
AppRoutingModule,
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: (createTranslateLoader),
deps: [HttpClient]
}
}),
],
providers: [
StatusBar,
SplashScreen,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
],
bootstrap: [AppComponent],
exports: [ TranslateModule ]
})
export class AppModule {}
**home.module.ts**
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { IonicModule } from '#ionic/angular';
import { FormsModule } from '#angular/forms';
import { RouterModule } from '#angular/router';
import { HomePage } from './home.page';
import { TranslateModule } from '#ngx-translate/core';
#NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
RouterModule.forChild([
{
path: '',
component: HomePage
}
]),
TranslateModule.forChild()
],
declarations: [HomePage]
})
export class HomePageModule {}
**auth.module.ts**
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { FormsModule } from '#angular/forms';
import { IonicModule } from '#ionic/angular';
import { AuthPage } from './auth.page';
import {TranslateModule} from '#ngx-translate/core';
#NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
TranslateModule.forChild()
],
declarations: [AuthPage]
})
export class AuthPageModule {}
I just pass the same issue and solved it, you should treat all your pages as LazyLoad just as you're actually doing in the home.module:
RouterModule.forChild([
{
path: '',
component: HomePage
}
]),
So in your auth.module the imports declaration must contain the RouterModule too:
RouterModule.forChild([
{
path: '',
component: AuthPage
}
])
...
That should do the trick and avoid the stack size exceeded. If you're using something as a SharedModule, I suggest you to add the TranslateModule in it to make it easier in your app structure:
import { TranslateModule } from '#ngx-translate/core';
#NgModule({
declarations: [],
imports: [
...
TranslateModule,
],
exports: [
...
TranslateModule,
]
})
export class SharedModule { }
Then in any of your next pages modules, just import the SharedModule and it's done:
imports: [
...
SharedModule,
]
Hope it helps!
So I have two components, ChartsComponent (renders charts) &
DataComponent (displays charts among other data, tables, etc).
The file system would be like:
app/charts/
app/entities/data/
ChartsComponent renders successfully when rendered into its own page with its own route. DataComponent works but can't render ChartsComponent through selector. Console displays no error at all. I tried to call ChartsComponent's selector in DataComponent like this:
data.component.html:
<chart-data></chart-data>
charts.component.html:
<div [chart]="chart1"></div>
charts.component.ts:
import { Component, OnInit} from '#angular/core';
import { Chart } from 'angular-highcharts';
//I'm loading data into the chart statically for trial
import { jsonData} from '../json-data/chart-data';
#Component({
selector: 'chart-data',
templateUrl: './charts.component.html'
})
export class ChartsComponent implements OnInit{
//Chart
chart1: Chart;
countries: any;
num: any;
chartData: any;
constructor() {
this.barChart();
}
ngOnInit(){}
barChart(){
this.chartData = jsonData;
this.chart1 = new Chart(this.chartData);
}
}
data.component.ts:
import { Component, OnInit, OnDestroy } from '#angular/core';
import { HttpResponse, HttpErrorResponse } from '#angular/common/http';
import { ActivatedRoute, Router } from '#angular/router';
import { DataService } from './provision.service';
import { ChartsComponent } from '../../charts/charts.component';
#Component({
selector: 'data-page',
templateUrl: './data.component.html'
})
export class DataComponent implements OnInit, OnDestroy {
}
charts.module.ts:
import { NgModule } from '#angular/core';
import { RouterModule } from '#angular/router';
import { ChartsComponent } from './';
#NgModule({
declarations: [
ChartsComponent
],
exports: [
ChartsComponent
]
})
export class ChartsModule {}
data.module.ts:
import { RouterModule } from '#angular/router';
import { ChartsModule } from '../../charts';
import { ChartsComponent } from '../../charts/charts.component';
import {
DataService,
DataComponent,
DataRoute
} from './';
#NgModule({
imports: [],
declarations: [DataComponent],
entryComponents: [
DataComponent,
ChartsComponent
],
providers: [
DataService
]
})
export class DataModule {}
charts/index.ts:
export * from './charts.component';
export * from './charts.module';
export * from './charts.route';
app.module.ts:
import './vendor.ts';
import { NgModule, Injector } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { HTTP_INTERCEPTORS } from '#angular/common/http';
import { Ng2Webstorage, LocalStorageService, SessionStorageService } from 'ngx-webstorage';
import { EventManager } from 'ng-blahblah';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations';
import { ChartModule } from 'angular-highcharts';
import { ChartsComponent } from './charts';
import { AuthInterceptor } from './blocks/interceptor/auth.interceptor';
import { AuthExpiredInterceptor } from './blocks/interceptor/auth-expired.interceptor';
import { ErrorHandlerInterceptor } from './blocks/interceptor/errorhandler.interceptor';
import { NotificationInterceptor } from './blocks/interceptor/notification.interceptor';
import { SharedModule, UserRouteAccessService } from './shared';
import { AppRoutingModule} from './app-routing.module';
import { HomeModule } from './home/home.module';
import { AdminModule } from './admin/admin.module';
import { AccountModule } from './account/account.module';
import { EntityModule } from './entities/entity.module';
import { PaginationConfig } from './blocks/config/uib-pagination.config';
import {
MainComponent,
NavbarComponent,
FooterComponent,
ProfileService,
PageRibbonComponent,
ActiveMenuDirective,
ErrorComponent
} from './layouts';
#NgModule({
imports: [
BrowserModule,
BrowserAnimationsModule,
AppRoutingModule,
SharedModule,
HomeModule
EntityModule,
ChartModule
],
declarations: [
MainComponent,
NavbarComponent,
ErrorComponent,
PageRibbonComponent,
ActiveMenuDirective,
FooterComponent,
ChartsComponent
],
providers: [
ProfileService,
PaginationConfig,
UserRouteAccessService,
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true,
deps: [
LocalStorageService,
SessionStorageService
]
},
{
provide: HTTP_INTERCEPTORS,
useClass: AuthExpiredInterceptor,
multi: true,
deps: [
Injector
]
},
{
provide: HTTP_INTERCEPTORS,
useClass: ErrorHandlerInterceptor,
multi: true,
deps: [
EventManager
]
},
{
provide: HTTP_INTERCEPTORS,
useClass: NotificationInterceptor,
multi: true,
deps: [
Injector
]
},
/*{
provide: NgbDateParserFormatter,
useFactory: () => { return new NgbDateMomentParserFormatter("DD-MM-YYYY") }
}*/
],
bootstrap: [ MainComponent ]
})
export class AppModule {}
I think that's all what's relevant, if someone could explain what's wrong, missing and why, it would be of great help. In the meanwhile I'll try to document myself better on the module/import system.
Ok so basically, the module.ts file in which you are going to import the ChartsComponent and the ChartModule (we are talking highcharts here) needs to also export ChartsComponent.
Import both, then under NgModule import ChartModule, and under declarations and exports tag ChartsComponent. On the destination data.module import ChartsComponent and tag it under NgModule - entryComponents. On the destination DataComponent import ChartsComponent.
I'm trying to use the Angular flash message module as shown in this post:
https://www.npmjs.com/package/angular-flash-message
However, I get this error:
> compiler.js:485 Uncaught Error: Template parse errors:
> 'flash-messages' is not a known element:
>
> 1. If 'flash-messages' is an Angular component, then verify that it is part of this module.
> 2. If 'flash-messages' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '#NgModule.schemas' of this component
> to suppress this message. ("<app-navbar></app-navbar><div
> class="container">[ERROR
> ->]<flash-messages></flash-messages><router-outlet></router-outlet> </div>"): ng:///AppModule/AppComponent.html#2:8
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { Routes, RouterModule } from '#angular/router';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NavbarComponent } from './components/navbar/navbar.component';
import { LoginComponent } from './components/login/login.component';
import { HomeComponent } from './components/home/home.component';
import { DashboardComponent } from './components/dashboard/dashboard.component';
import { ProfileComponent } from './components/profile/profile.component';
import { RegisterComponent } from './components/register/register.component';
import { ValidateService } from './services/validate.service';
import {FlashMessageModule} from 'angular-flash-message'
#NgModule({
declarations: [
AppComponent,
NavbarComponent,
LoginComponent,
HomeComponent,
DashboardComponent,
ProfileComponent,
RegisterComponent
],
imports: [
BrowserModule,
AppRoutingModule,
RouterModule,
FormsModule,
FlashMessageModule
],
providers: [ValidateService],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.html
<app-navbar></app-navbar>
<div class="container">
<flash-messages></flash-messages>
<router-outlet></router-outlet>
</div>
registration.component.ts
import { Component, OnInit } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { ValidateService } from '../../services/validate.service';
import { FlashMessage } from 'angular-flash-message';
#Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.scss']
})
export class RegisterComponent implements OnInit {
name: String;
username: String;
email: String;
password: String;
constructor(
private validateService: ValidateService,
private flashMessage: FlashMessage
) { }
ngOnInit() {
}
onRegisterSubmit(){
const user = {
name: this.name,
username: this.username,
email: this.email,
password: this.password
}
//Required fields
if(!this.validateService.validateRegister(user)){
//fill in all fields
this.flashMessage.info("Incorrect!")
return false;
}
if(!this.validateService.validateEmail(user.email)){
//email incorrect
return false;
}
}
}
I'm trying to display a flash message after validating the user's input.
I'm new to Angular and MEAN apps and this is actually an app shown in a tutorial using Angular 2.
Can someone help me out? Thanks!
I'm not sure if the
import {FlashMessageModule} from 'angular-flash-message'
works properly. I would suggest using
import {FlashMessageModule} from 'angular2-flash-messages'`.
Their documentation is here: https://www.npmjs.com/package/angular2-flash-messages
I went through the angular-flash messages docs, angular2-flash-message docs (without the 's' at the end), and also angular2-flash-messages (with the 's' at the end), and the only one that worked for me was the last one.
Also, in addition to your imports, I've also found that it helps to make sure you have #angular/common installed, just in case:
npm install #angular/common --save
Hope this helps
ooh i think it shouldn't be
ERRONEOUS
imports: [
BrowserModule,
FormsModule,
RouterModule.forRoot(appRoutes),
AngularFireModule.initializeApp(fireBase),
FlashMessagesModule
],
it should be
imports: [
BrowserModule,
FormsModule,
RouterModule.forRoot(appRoutes),
AngularFireModule.initializeApp(fireBase),
FlashMessagesModule.forRoot()
],
I too had the same problem and solved it by adding FlashMessageModule.forRoot() in my imports