I follow nativescript-ui-samples-angular https://github.com/NativeScript/nativescript-ui-samples-angular
and can see charts when running the application. When I use the same code in my application, there is no chart showing up on IOS and Android. I have no idea what's wrong. Do I miss some configurations? Thanks
chart.component.html
<RadCartesianChart tkExampleTitle tkToggleNavButton>
<CategoricalAxis tkCartesianHorizontalAxis lastLabelVisibility="Hidden" ios:firstLabelVisibility="Hidden"
ios:plotMode="OnTicks">
</CategoricalAxis>
<LinearAxis tkCartesianVerticalAxis></LinearAxis>
<AreaSeries tkCartesianSeries [items]="categoricalSource" categoryProperty="Country" valueProperty="Amount">
</AreaSeries>
</RadCartesianChart>
chart.component.ts
import { Component,ElementRef, ViewChildren, QueryList, OnInit } from "#angular/core";
import { ObservableArray } from "tns-core-modules/data/observable-array";
import { DataService } from "./data.service";
import { Country } from "./country";
#Component({
selector: "ns-charts",
moduleId: module.id,
templateUrl: "./chart.component.html",
styleUrls: ['./chart.component.css']
})
export class ChartComponent implements OnInit {
private _categoricalSource: ObservableArray<Country>;
constructor(private _dataService: DataService) { }
get categoricalSource(): ObservableArray<Country> {
return this._categoricalSource;
}
ngOnInit() {
this._categoricalSource = new ObservableArray(this._dataService.getCategoricalSource());
console.log(this._categoricalSource);
}
}
country.ts
export class Country {
constructor(public Country?: string, public Amount?: number, public SecondVal?: number, public ThirdVal?: number, public Impact?: number, public Year?: number) {
}
}
data.service.ts
import { Country } from "./country";
import { Injectable } from '#angular/core';
#Injectable()
export class DataService {
getCategoricalSource(): Country[] {
return [
{ Country: "Germany", Amount: 15, SecondVal: 14, ThirdVal: 24, Impact: 0, Year: 0 },
{ Country: "France", Amount: 13, SecondVal: 23, ThirdVal: 25, Impact: 0, Year: 0 },
{ Country: "Bulgaria", Amount: 24, SecondVal: 17, ThirdVal: 23, Impact: 0, Year: 0 },
{ Country: "Spain", Amount: 11, SecondVal: 19, ThirdVal: 24, Impact: 0, Year: 0 },
{ Country: "USA", Amount: 18, SecondVal: 8, ThirdVal: 21, Impact: 0, Year: 0 }
];
}
}
app-routing.module.ts
import { NgModule } from "#angular/core";
import { NativeScriptRouterModule } from "nativescript-angular/router";
import { Routes } from "#angular/router";
import { ChartComponent } from "./chart/chart.component";
const routes: Routes = [
{ path: "", redirectTo: "/charts", pathMatch: "full" },
{ path: "charts", component: ChartComponent }
];
#NgModule({
imports: [NativeScriptRouterModule.forRoot(routes)],
exports: [NativeScriptRouterModule]
})
export class AppRoutingModule { }
package.json
{
"nativescript": {
"id": "org.nativescript.boardgamehelper",
"tns-android": {
"version": "6.0.1"
},
"tns-ios": {
"version": "6.0.1"
}
},
"description": "NativeScript Application",
"license": "SEE LICENSE IN <your-license-filename>",
"repository": "<fill-your-repository-here>",
"dependencies": {
"#angular/animations": "~8.0.0",
"#angular/common": "~8.0.0",
"#angular/compiler": "~8.0.0",
"#angular/core": "~8.0.0",
"#angular/forms": "~8.0.0",
"#angular/http": "~8.0.0-beta.10",
"#angular/platform-browser": "~8.0.0",
"#angular/platform-browser-dynamic": "~8.0.0",
"#angular/router": "~8.0.0",
"nativescript-angular": "~8.0.0",
"nativescript-theme-core": "~1.0.4",
"nativescript-ui-chart": "^5.0.0",
"reflect-metadata": "~0.1.12",
"rxjs": "~6.5.0",
"tns-core-modules": "6.0.2",
"zone.js": "~0.9.1"
},
"devDependencies": {
"#angular/compiler-cli": "~8.0.0",
"#ngtools/webpack": "~8.0.0",
"nativescript-dev-webpack": "~1.0.0",
"typescript": "3.4.5"
},
"gitHead": "8c1a4866a66daab09bf5ef8e5a96472687192373",
"readme": "NativeScript Application"
}
You have to import the chart module in your module.ts e.g
import { NativeScriptUIChartModule } from "nativescript-ui-chart/angular";
Related
I'm getting a compilation error when trying to run nuxt with vuetify. It says that vuetify.css was not found with the dependency absolute path. I checked in buildDir/App.js and vuetify.css is the only dependency to reference a fullpath. Is there a reason to that ?
What do I miss ?
yarn dev
This dependency was not found: friendly-errors 10:34:11
friendly-errors 10:34:11
* .\full\path\to\myproject\src\node_modules\vuetify\dist\vuetify.css in ./myproject/prod/server/nuxt/App.js
friendly-errors 10:34:11
To install it, you can run: npm install --save .\full\path\to\myproject\src\node_modules\vuetify\dist\vuetify.css
buildDir/App.js
...
import '..\\..\\..\\src\\assets\\main.css'
import '..\\..\\..\\src\\assets\\variables.scss'
import '.\\full\\path\\to\\myproject\\src\\node_modules\\vuetify\\dist\\vuetify.css'
import _6f6c098b from '..\\..\\..\\src\\layouts\\default.vue'
...
package.json
"dependencies": {
"#nuxtjs/axios": "^5.9.2",
"#nuxtjs/firebase": "^4.1.0",
"firebase": "^7.10.0",
"lodash": "^4.17.15",
"nuxt": "^2.0.0",
"nuxt-i18n": "^6.5.0"
},
"devDependencies": {
"#babel/runtime-corejs3": "^7.8.7",
"#nuxtjs/dotenv": "^1.4.1",
"#nuxtjs/vuetify": "^1.11.0",
"#vue/test-utils": "^1.0.0-beta.27",
"babel-jest": "^24.1.0",
"core-js": "3",
"eslint": "^6.8.0",
"eslint-config-prettier": "^6.9.0",
"eslint-plugin-prettier": "^3.0.1",
"jest": "^24.9.0",
"prettier": "^1.16.4",
"vue-jest": "^4.0.0-0"
}
nuxt.config.js
import webpack from 'webpack'
require('dotenv').config({ path: '../.env' })
export default {
mode: 'universal',
server: {
host: process.env.HOST_NAME,
port: process.env.HOST_PORT
},
env: process.env,
head: {
titleTemplate: '%s - ' + process.env.npm_package_name,
title: process.env.npm_package_name || '',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: process.env.npm_package_description || '' }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
{ rel: 'stylesheet', href: 'https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900' },
]
},
loading: { color: '#fff' },
css: [
'#/assets/main.css',
'#/assets/variables.scss'
],
plugins: [],
buildModules: [
['#nuxtjs/vuetify', { }],
['#nuxtjs/dotenv', { path: '../', filename: '.env' }]
],
modules: [],
vuetify: {
customVariables: ['~/assets/variables.scss'],
optionsPath: "./vuetify.options.js",
},
buildDir: "../prod/server/nuxt",
build: {
plugins: [
new webpack.ProvidePlugin({
'_': 'lodash'
})
],
extractCSS: true,
extend (config, ctx) {},
babel: {
presets({ isServer }) {
return [
[
require.resolve('#nuxt/babel-preset-app'),
{
buildTarget: isServer ? 'server' : 'client',
corejs: { version: 3 }
}
]
]
}
}
}
}
I need to get family list of user
my Api get this
this is the data we get
{
"id": 16,
"username": "omar",
"gender": "male",
"age": 39,
"knownAs": "Omar Talaat",
"created": "2017-07-11T00:00:00",
"lastActive": "2020-02-19T16:51:50.0251608",
"phoneNumber": null,
"mobileNumber": "0114006884",
"city": "October city ",
"country": "Egypt",
"photoUrl": "http://res.cloudinary.com/drm7h8ge0/image/upload/v1577009358/wk0k06fkbbkt0vbnjvic.jpg",
"photos": [
{
"id": 9,
"url": ,
"description": null,
"dateAdded": "2019-12-22T12:09:16.9949907",
"isMain": true
},
{
"id": 1007,
"url":,
"description": null,
"dateAdded": "2019-12-26T01:26:48.8852864",
"isMain": false
}
],
"families": [
{
"id": 1028,
"familyName": "Othman",
"father": {
"id": 1028,
"firstName": "Omar Talaat",
"lastName": "Othman",
"job": " pharmasict",
"mobileNumber": 1254879,
"emailAdress": "domar#yahoo.com",
"isExest": true
},
"mother": {
"id": 1028,
"firstName": "marium",
"lastName": "Abd Rabo ",
"job": "Doctor",
"mobileNumber": 1254879,
"emailAdress": "maruim#htomail",
"isExest": true
},
"addresses": [
{
"addressName": "1 kdsk kjhduu",
"city": " october city",
"country": "Egypt"
}
]
},
{
"id": 1029,
"familyName": "update-talaat",
"father": {
"id": 1029,
"firstName": "omar",
"lastName": "talaat",
"job": "update-farmacist",
"mobileNumber": 21547,
"emailAdress": "omar#gmail.com",
"isExest": false
},
"mother": {
"id": 1029,
"firstName": "marium",
"lastName": "gonzales",
"job": "update-doctor",
"mobileNumber": 13654,
"emailAdress": "mariumgonzales#hotmail.com",
"isExest": true
},
"addresses": [
{
"addressName": "1,update- mohamed streest ",
"city": "giza",
"country": "egypt"
}
]
}
]
}
interface for user:-
import { Photo } from './photo';
import { Family } from './family';
export interface User {
id: number;
num: number;
username: string;
knownAs: string;
age: number;
gender: string;
created: Date;
lastActive: Date;
photoUrl: string;
city: string;
country: string;
emailAdress: string;
phoneNumber: string;
mobileNumber: string;
photos?: Photo[];
family?: Family[];
}
family interface:-
import { Address } from './address';
import { Father } from './father';
import { Mother } from './mother';
export interface Family {
id: number;
familyName: string;
father: Father;
mother: Mother;
addresses: Address[];
}
and my user service like that:
baseUrl = environment.apiUrl;
users: User[];
constructor( private http: HttpClient , private authService: AuthService) { }
getUsers(): Observable<User[]> {
return this.http.get<User[]>(this.baseUrl + 'users' );
}
getUser(id: number): Observable<User> {
return this.http.get<User>(this.baseUrl + 'users/' + id);
}
getFamilies(): Observable<Family[]> {
return this.http.get<Family[]>(this.baseUrl + 'users/' + this.authService.decodedToken.nameid + '/families' );
}
getFamily( id): Observable<Family> {
return this.http.get<Family>(this.baseUrl + 'users/' + this.authService.decodedToken.nameid + '/families/' + id);
}
this is MemberDetailsResolver :-
import { Injectable } from '#angular/core';
import { Resolve, ActivatedRouteSnapshot, Router } from '#angular/router';
import { User } from '../_models/user';
import { Observable, of } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { UserService } from '../_service/user.service';
import { AlertifyService } from '../_service/alertify.service';
import { AuthService } from '../_service/auth.service';
#Injectable(
)
export class MemberDetailsResolver implements Resolve<User> {
constructor(private userService: UserService, private router: Router,
private alertify: AlertifyService , private authService: AuthService) {}
resolve(route: ActivatedRouteSnapshot): Observable<User> {
return this.userService.getUser(this.authService.decodedToken.nameid).pipe(
catchError(error => {
this.alertify.error('Proplem retriving data');
this.router.navigate(['/CampList']);
return of(null);
})
);
}
}
this my member family card component:-
import { Component, OnInit, Input } from '#angular/core';
import { Family } from 'src/app/_models/family';
import { User } from 'src/app/_models/user';
#Component({
selector: 'app-member-family-card',
templateUrl: './member-family-card.component.html',
styleUrls: ['./member-family-card.component.css']
})
export class MemberFamilyCardComponent implements OnInit {
#Input() family: Family[];
constructor() { }
ngOnInit() {
}
}
member family card html:-
<div *ngFor="let family of family">
<div class="card mb-4"style="max-width: 202px;" >
<!-- Image -->
<div class="car-img-wrapper">
<img class="card-img-top" src="{{'../../../assets/img/person-placeholder.jpg'}}">
<ul class="list-inline member-icons animate text-center">
<li class="list-inline-item"><button class="btn btn-primary" [routerLink]="['/family/',family.id]" ><i class="fa fa-user"></i></button></li>
<!--
<li class="list-inline-item"><button class="btn btn-primary"
[routerLink]="['/members/',family.id]" [queryParams]="{tab : 3}" ><i class="fa fa-envelope"></i></button></li>
-->
</ul>
</div>
<div class="card-body p-1">
<h5 class="card-title text-center mb-1"><i class="fa fa-user"></i><strong>Family Name: </strong>{{family.familyName}}</h5>
</div>
</div>
</div>
this member details:-
import { Component, OnInit, Input, ViewChild } from '#angular/core';
import { User } from 'src/app/_models/user';
import { FakeMissingTranslationHandler } from '#ngx-translate/core';
import { Family } from 'src/app/_models/family';
import { TabsetComponent } from 'ngx-bootstrap';
import { ActivatedRoute } from '#angular/router';
import { UserService } from 'src/app/_service/user.service';
import { AlertifyService } from 'src/app/_service/alertify.service';
import { NgxGalleryOptions, NgxGalleryImage, NgxGalleryAnimation } from 'ngx-gallery';
#Component({
selector: 'app-member-details',
templateUrl: './member-details.component.html',
styleUrls: ['./member-details.component.css']
})
export class MemberDetailsComponent implements OnInit {
#ViewChild('memberTabs', {static: true}) memberTabs: TabsetComponent;
user: User;
galleryOptions: NgxGalleryOptions[];
galleryImages: NgxGalleryImage[];
constructor(private userService: UserService, private alertify: AlertifyService, private route: ActivatedRoute) { }
ngOnInit() {
this.route.data.subscribe(data => {
this.user = data.user;
});
this.route.queryParams.subscribe(params => {
const selectTab = params.tab;
this.memberTabs.tabs[selectTab > 0 ? selectTab : 0].active = true;
});
this.galleryOptions = [
{
width: '500px',
height: '500px',
imagePercent: 100,
thumbnailsColumns: 4,
imageAnimation: NgxGalleryAnimation.Slide,
preview: false
}
];
this.galleryImages = this.user.photos.map(photo => ({
small: photo.url,
medium: photo.url,
big: photo.url,
description: photo.description
})
);
}
selectTab(tabId: number) {
this.memberTabs.tabs[tabId].active = true;
}
}
this is member details html
<div class="container-fluid mt-4">
<div >
<h1> your Profile </h1>
<div class="row">
<div class="col-sm-4">
<app-member-card [user]="user"></app-member-card>
</div>
<div class="col-sm-8">
<div class="tab-panel">
<tabset class="member-tabset" #memberTabs>
<tab heading="My Detailes">
</tab>
<tab heading=" My Photos" >
<ngx-gallery [options]="galleryOptions" [images]="galleryImages"></ngx-gallery>
</tab>
<tab heading="family">
<h4>Family detailes</h4>
<app-member-family-card [family]="user.family"></app-member-family-card>
</tab>
<tab heading="My Child">
<h4>my Child</h4>
</tab>
</tabset>
</div>
</div>
</div>
</div>
</div>
I want to display the family for user
Is there anyone knows a link which shows an example on how to implement itemSelecting in Nativescript angular RadListViewhttps://docs.nativescript.org/ns-ui-api-reference/classes/radlistview#itemselecting?
Because I can't find any example. Thank you.
HTML
<RadListView class="list-group" [items]="countries" selectionBehavior="Press"
multipleSelection="true" (itemSelecting)="onItemSelecting($event)"
(itemDeselecting)="onItemSelecting($event)">
<ng-template let-country="item">
<FlexboxLayout flexDirection="row" class="list-group-item">
<Image [src]="country.imageSrc" class="thumb img-circle"></Image>
<Label [text]="country.name" class="list-group-item-heading"
verticalAlignment="center" style="width: 60%"></Label>
</FlexboxLayout>
</ng-template>
</RadListView>
TS
import { ListViewEventData } from "nativescript-ui-listview"
import { Component } from "#angular/core";
#Component({
selector: "Home",
moduleId: module.id,
templateUrl: "./home.component.html",
styleUrls: ["./home.component.css"]
})
export class HomeComponent {
countries: { name: string, imageSrc: string }[] = [
{ name: "Australia", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/au.png" },
{ name: "Belgium", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/be.png" },
{ name: "Bulgaria", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/bg.png" },
{ name: "Canada", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/ca.png" },
{ name: "Switzerland", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/ch.png" },
{ name: "China", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/cn.png" },
{ name: "Czech Republic", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/cz.png" },
{ name: "Germany", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/de.png" },
{ name: "Spain", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/es.png" },
{ name: "Ethiopia", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/et.png" },
{ name: "Croatia", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/hr.png" },
{ name: "Hungary", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/hu.png" },
{ name: "Italy", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/it.png" },
{ name: "Jamaica", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/jm.png" },
{ name: "Romania", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/ro.png" },
{ name: "Russia", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/ru.png" },
{ name: "United States", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/us.png" },
];
onItemSelecting(args: ListViewEventData): void {
console.log(args.view.bindingContext.name);
args.returnValue = args.index > 5;
}
}
Note: It seems to be buggy, at least on Android. Second tap fails to fire itemSelecting event and marks the item as selected. A workaround could be found at nativescript-ui-feedback/issues/181
I started getting this error once I upgraded to Webpack and related dependencies to v4: [Vue warn]: Failed to mount component: template or render function not defined.
Here's the relevant snippets of my package.json and webpack.config.js before and after:
Before upgrade:
package.json
{
"dependencies": {
"vue": "^2.5.0",
"vue-template-compiler": "^2.5.0"
},
"devDependencies": {
"babel-core": "^6.9.0",
"babel-loader": "^6.2.4",
"babel-plugin-external-helpers": "^6.22.0",
"babel-plugin-transform-es2015-block-scoping": "^6.26.0",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-env": "^1.6.1",
"babel-preset-es2015": "^6.9.0",
"babel-preset-es2015-without-strict": "^0.0.4",
"babel-preset-es2017": "^6.24.1",
"babel-preset-latest": "^6.24.1",
"css-loader": "^0.26.0",
"eslint": "^4.3.0",
"husky": "^0.14.3",
"lint-staged": "^4.0.2",
"resolve-url-loader": "^1.6.0",
"sass-loader": "^4.0.1",
"stats-webpack-plugin": "^0.2.1",
"style-loader": "^0.13.1",
"uglifyjs-webpack-plugin": "^1.1.6",
"vue-loader": "^12.1.0",
"webpack": "3.10.0",
"webpack-dev-server": "^2.3.0",
"webpack-monitor": "^1.0.13"
}
}
webpack.config.js
{
resolve: {
modules: [
path.join(__dirname, '..', 'webpack'),
'node_modules/'
],
alias: {
vue: process.env.NODE_ENV === 'production' ? 'vue/dist/vue.min.js' : 'vue/dist/vue.js',
libs: 'libs/'
}
},
plugins: [
new StatsPlugin('manifest.json', {
chunkModules: false,
source: false,
chunks: false,
modules: false,
assets: true
})],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
cacheDirectory: true,
presets: ['es2015']
}
}
]
}, {
test: /\.vue$/,
exclude: /node_modules/,
use: [
{
loader: 'vue-loader'
}
]
},
{
test: /\.js$/,
include: [
path.resolve(process.cwd(), 'node_modules/')
],
use: [
{
loader: 'babel-loader',
options: {
plugins: ['transform-es2015-block-scoping'],
cacheDirectory: true
}
}
],
},
]
}
};
After upgrade:
package.json
{
"dependencies": {
"vue": "^2.5.13",
"vue-template-compiler": "^2.5.13"
},
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.3",
"babel-plugin-external-helpers": "^6.22.0",
"babel-preset-env": "^1.6.1",
"babel-preset-latest": "^6.24.1",
"css-loader": "^0.26.0",
"eslint": "^4.3.0",
"husky": "^0.14.3",
"lint-staged": "^4.0.2",
"resolve-url-loader": "^1.6.0",
"sass-loader": "^4.0.1",
"stats-webpack-plugin": "^0.2.1",
"style-loader": "^0.13.1",
"uglifyjs-webpack-plugin": "^1.1.6",
"vue-loader": "^14.1.1",
"webpack": "^4.0.1",
"webpack-cli": "^2.0.9",
"webpack-dev-server": "^3.0.0",
"webpack-monitor": "^1.0.13"
}
}
webpack.config.js
{
resolve: {
modules: [
path.join(__dirname, '..', 'webpack'),
'node_modules/'
],
alias: {
vue: process.env.NODE_ENV === 'production' ? 'vue/dist/vue.min.js' : 'vue/dist/vue.js',
libs: 'libs/'
}
},
plugins: [
new StatsPlugin('manifest.json', {
chunkModules: false,
source: false,
chunks: false,
modules: false,
assets: true
})],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
cacheDirectory: true
}
}
]
}, {
test: /\.vue$/,
exclude: /node_modules/,
use: [
{
loader: 'vue-loader'
}
]
},
{
test: /\.js$/,
include: [
path.resolve(process.cwd(), 'node_modules/')
],
use: [
{
loader: 'babel-loader',
options: {
cacheDirectory: true
}
}
],
},
]
}
};
What is expected?
Vue components work without errors after upgrading
What is actually happening?
Most Vue components show an error and fail to load: [Vue warn]: Failed to mount component: template or render function not defined.
Figured this out (h/t #skribe). Basically I was declaring components like this:
Vue.component('thing', require('libs/components/thing.vue'));
I had to change that to:
Vue.component('thing', require('libs/components/thing.vue').default);
My Angular application is working properly, but I am keep getting Karma error when I run ng test command. I have attached app component, spec, module and html along with package.json file. Error looks like this:
Failed: No provider for ChildrenOutletContexts!
Error: No provider for ChildrenOutletContexts!
at injectionError (http://localhost:9876/_karma_webpack_/vendor.bundle.js:39523:90)
at noProviderError (http://localhost:9876/_karma_webpack_/vendor.bundle.js:39561:12)
at ReflectiveInjector_.webpackJsonp.../../../core/#angular/core.es5.js.ReflectiveInjector_._throwOrNull (http://localhost:9876/_karma_webpack_/vendor.bundle.js:41003:19)
at ReflectiveInjector_.webpackJsonp.../../../core/#angular/core.es5.js.ReflectiveInjector_._getByKeyDefault (http://localhost:9876/_karma_webpack_/vendor.bundle.js:41042:25)
at ReflectiveInjector_.webpackJsonp.../../../core/#angular/core.es5.js.ReflectiveInjector_._getByKey (http://localhost:9876/_karma_webpack_/vendor.bundle.js:40974:25)
at ReflectiveInjector_.webpackJsonp.../../../core/#angular/core.es5.js.ReflectiveInjector_.get (http://localhost:9876/_karma_webpack_/vendor.bundle.js:40843:21)
at resolveNgModuleDep (http://localhost:9876/_karma_webpack_/vendor.bundle.js:47827:25)
at NgModuleRef_.webpackJsonp.../../../core/#angular/core.es5.js.NgModuleRef_.get (http://localhost:9876/_karma_webpack_/vendor.bundle.js:48909:16)
at resolveDep (http://localhost:9876/_karma_webpack_/vendor.bundle.js:49412:45)
at createClass (http://localhost:9876/_karma_webpack_/vendor.bundle.js:49276:32)
app.component.ts
import { Component } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.less']
})
export class AppComponent {
title = 'app';
}
app.component.html
Dashboard
User
<router-outlet></router-outlet>
app.component.spec.ts
import { TestBed, async } from '#angular/core/testing';
import { RouterModule, Routes } from '#angular/router';
import { FormsModule } from '#angular/forms';
import { APP_BASE_HREF } from '#angular/common';
import { AppComponent } from './app.component';
import { DashboardComponent } from './modules/dashboard/dashboard.component';
describe('AppComponent', () => {
const routes: Routes = [
{
path: '',
redirectTo: 'dashboard',
pathMatch: 'full'
},
{
path: 'dashboard',
component: DashboardComponent,
},
{
path: 'user',
loadChildren: 'app/modules/user/user.module#UserModule'
}
];
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterModule,
FormsModule
],
declarations: [
AppComponent,
DashboardComponent
],
providers: [
{ provide: APP_BASE_HREF, useClass: routes }
]
}).compileComponents();
}));
it('should create the app', async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
}));
it('should have as title app', async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app.title).toEqual('app');
}));
it('should render title in a h1 tag', async(() => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('h1').textContent).toContain('Welcome to app!!');
}));
});
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { RouterModule, Routes } from '#angular/router';
import { AppComponent } from './app.component';
import { DashboardComponent } from './modules/dashboard/dashboard.component';
const routes: Routes = [
{
path: '',
redirectTo: 'dashboard',
pathMatch: 'full'
},
{
path: 'dashboard',
component: DashboardComponent,
},
{
path: 'user',
loadChildren: 'app/modules/user/user.module#UserModule'
}
];
#NgModule({
declarations: [
AppComponent,
DashboardComponent,
],
imports: [
BrowserModule,
FormsModule,
RouterModule.forRoot(routes)
],
providers: [],
bootstrap: [AppComponent],
exports: [RouterModule]
})
export class AppModule { }
package.json
...
"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",
"core-js": "^2.4.1",
"rxjs": "^5.1.0",
"zone.js": "0.8.12"
},
"devDependencies": {
"#angular/cli": "1.2.1",
"#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",
....
Based on the clue provided by #John, I imported RouterTestingModule instead of importing RouterModule and APP_BASE_HREF. So, the following modification in app.component.spec.ts worked!
import { TestBed, async } from '#angular/core/testing';
import { FormsModule } from '#angular/forms';
import { RouterTestingModule } from '#angular/router/testing';
import { AppComponent } from './app.component';
import { DashboardComponent } from './modules/dashboard/dashboard.component';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule
FormsModule
],
declarations: [
AppComponent,
DashboardComponent
]
}).compileComponents();
}));