Angular <mat-expansion-panel-header> does not expand - angular-material

I am learning Angular and using Material for Angular for styling. For some reason the mat-accordian isn't working for me.
<mat-accordion>
<mat-expansion-panel >
<mat-expansion-panel-header>
<mat-panel-title>
<h2>Post 1</h2>
</mat-panel-title>
<mat-panel-description>
<p>Post 1 Content</p>
</mat-panel-description>
</mat-expansion-panel-header>
<p>I'm in an expansion panel</p>
</mat-expansion-panel>
</mat-accordion>
import { NgModule } from '#angular/core';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations';
import { BrowserModule } from '#angular/platform-browser';
import {
MatInputModule,
MatCardModule,
MatButtonModule,
MatToolbarModule,
MatExpansionModule
} from '#angular/material/';
import { AppComponent } from './app.component';
import { FormsModule } from '#angular/forms';
import { PostCreateComponent } from './posts/post-create/post-create.component';
import { HeaderComponent } from './header/header.component';
import { PostListComponent } from './posts/post-create/post-list/post-list.component';
#NgModule({
declarations: [
AppComponent,
PostCreateComponent,
HeaderComponent,
PostListComponent,
],
imports: [
BrowserModule,
BrowserAnimationsModule,
FormsModule,
MatInputModule,
MatCardModule,
MatButtonModule,
MatToolbarModule,
MatExpansionModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
"dependencies": {
"#angular/animations": "^14.2.0",
"#angular/common": "^14.2.0",
"#angular/compiler": "^14.2.0",
"#angular/core": "^14.2.0",
"#angular/forms": "^14.2.0",
"#angular/material": "^7.0.0",
"#angular/cdk": "^7.0.0",
"#angular/platform-browser": "^14.2.0",
"#angular/platform-browser-dynamic": "^14.2.0",
"#angular/router": "^14.2.0",
"rxjs": "~7.5.0",
"tslib": "^2.3.0",
"zone.js": "~0.11.4"
I've tried reading other posts on stack overflow but nothing has seemed to work.
I tried installing with
import {MatExpansionModule} from '#angular/material/expansion';
but this doesn't work. The accordion is just forever open. Does anyone with Angular experience know where I am going wrong?

Solved: If you install using the default installation and there are peer dependencies it will install an earlier version of Angular Material.
To Fix the issue I uninstalled Angular globally, cleared the cache, then reinstalled, and was able to resolve the dependency conflicts and install the latest version.

Related

Angularfire does not work on ionic capacitor app on ios

I am using ionic with capacitor and angularfire. It works fine but does not work on ios. On ios I don't see any error - just the firebase call that never returns anything. Below is my package.json and other relevant info.
ionic.info:
ionic info
Ionic:
Ionic CLI : 6.18.1 (/usr/local/lib/node_modules/#ionic/cli)
Ionic Framework : #ionic/angular 5.9.1
#angular-devkit/build-angular : 12.1.4
#angular-devkit/schematics : 12.1.4
#angular/cli : 12.1.4
#ionic/angular-toolkit : 4.0.0
Capacitor:
Capacitor CLI : 3.3.2
#capacitor/android : 3.3.2
#capacitor/core : 3.3.2
#capacitor/ios : 3.3.2
Cordova:
Cordova CLI : 10.0.0 (cordova-lib#10.1.0)
Cordova Platforms : android broken, ios 5.1.1
Cordova Plugins : no whitelisted plugins (0 plugins total)
Utility:
cordova-res (update available: 0.15.4) : 0.15.3
native-run : 1.5.0
System:
ios-deploy : 1.9.4
ios-sim : ios-sim/9.0.0 darwin-x64 node-v14.17.0
NodeJS : v14.17.0 (/usr/local/bin/node)
npm : 7.24.0
OS : macOS Monterey
Xcode : Xcode 13.1 Build version 13A1030d
Package.json:
"dependencies": {
"#angular/common": "~12.1.1",
"#angular/core": "~12.1.1",
"#angular/fire": "^7.2.0",
"#angular/forms": "~12.1.1",
"#angular/platform-browser": "~12.1.1",
"#angular/platform-browser-dynamic": "~12.1.1",
"#angular/router": "~12.1.1",
"#capacitor/android": "^3.3.2",
"#capacitor/app": "^1.0.6",
"#capacitor/browser": "^1.0.6",
"#capacitor/core": "3.3.2",
"#capacitor/device": "^1.1.0",
"#capacitor/haptics": "^1.1.3",
"#capacitor/ios": "^3.3.2",
"#capacitor/keyboard": "^1.1.3",
"#capacitor/splash-screen": "^1.1.6",
"#capacitor/status-bar": "^1.0.6",
"#capacitor/storage": "^1.2.3",
"#ionic-native/app-version": "^5.36.0",
"#ionic-native/barcode-scanner": "^5.36.0",
"#ionic-native/call-number": "^5.36.0",
"#ionic-native/camera": "^5.36.0",
"#ionic-native/camera-preview": "^5.36.0",
"#ionic-native/contacts": "^5.36.0",
"#ionic-native/email-composer": "^5.36.0",
"#ionic-native/in-app-browser": "^5.36.0",
"#ionic-native/in-app-purchase": "^5.36.0",
"#ionic-native/in-app-purchase-2": "^5.36.0",
"#ionic-native/social-sharing": "^5.36.0",
"#ionic/angular": "^5.5.2",
"#ngx-translate/core": "^11.0.1",
"#ngx-translate/http-loader": "^4.0.0",
"call-number": "^1.0.1",
"cordova-plugin-app-version": "^0.1.12",
"cordova-plugin-camera": "^6.0.0",
"cordova-plugin-camera-preview": "^0.12.3",
"cordova-plugin-contacts": "^3.0.1",
"cordova-plugin-email-composer": "^0.10.0",
"cordova-plugin-inappbrowser": "^5.0.0",
"cordova-plugin-inapppurchase": "^1.2.0",
"cordova-plugin-purchase": "^10.6.1",
"cordova-plugin-x-socialsharing": "^6.0.3",
"firebase": "^9.5.0",
"forcejs": "^2.2.1",
"phonegap-plugin-barcodescanner": "^8.1.0",
"rxjs": "~6.6.0",
"tslib": "^2.2.0",
"xcode": "^3.0.1",
"xml-js": "^1.6.11",
"zone.js": "~0.11.4"
},
"devDependencies": {
"#angular-devkit/build-angular": "~12.1.1",
"#angular-eslint/builder": "~12.0.0",
"#angular-eslint/eslint-plugin": "~12.0.0",
"#angular-eslint/eslint-plugin-template": "~12.0.0",
"#angular-eslint/template-parser": "~12.0.0",
"#angular/cli": "~12.1.1",
"#angular/compiler": "~12.1.1",
"#angular/compiler-cli": "~12.1.1",
"#angular/language-service": "~12.0.1",
"#capacitor/cli": "3.3.2",
"#ionic/angular-toolkit": "^4.0.0",
"#types/jasmine": "~3.6.0",
"#types/jasminewd2": "~2.0.3",
"#types/node": "^12.11.1",
"#typescript-eslint/eslint-plugin": "4.16.1",
"#typescript-eslint/parser": "4.16.1",
"es6-promise-plugin": "^4.2.2",
"eslint": "^7.6.0",
"eslint-plugin-import": "2.22.1",
"eslint-plugin-jsdoc": "30.7.6",
"eslint-plugin-prefer-arrow": "1.2.2",
"jasmine-core": "~3.8.0",
"jasmine-spec-reporter": "~5.0.0",
"karma": "~6.3.2",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage": "~2.0.3",
"karma-coverage-istanbul-reporter": "~3.0.2",
"karma-jasmine": "~4.0.0",
"karma-jasmine-html-reporter": "^1.5.0",
"protractor": "~7.0.0",
"ts-node": "~8.3.0",
"typescript": "~4.2.4"
}
app.module.ts:
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { RouteReuseStrategy } from '#angular/router';
import { AngularFireModule } from '#angular/fire/compat';
import { AngularFireDatabaseModule } from '#angular/fire/compat/database';
import { IonicModule, IonicRouteStrategy } from '#ionic/angular';
import { FormsModule } from '#angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
#NgModule({
declarations: [
AppComponent,
],
entryComponents: [
],
imports: [
AngularFireModule.initializeApp(firebaseConfig),
AngularFireDatabaseModule,
BrowserModule,
HttpClientModule,
IonicModule.forRoot(),
AppRoutingModule,
FormsModule,
],
providers: [
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
],
bootstrap: [AppComponent]
})
export class AppModule {}
The code that never executes and no error in catch block is below. Same works just fine on android:
const resp:any = await this.dataSvc.getSeedConfig()
console.log("seed config is::" + JSON.stringify(resp))
So the above code does not go to the catch block and does not print the seed config on ios. Works fine on android.
Also on ios it works using live reload using
ionic capacitor run ios -l --external
so if i run it using xcode then it does not work. not sure what is blocking in that specific case
Already answered this here https://stackoverflow.com/a/70594992/5701521 but could be useful to answer it here as well.
Been struggling a lot with this issue too but I managed to fix it. For those who need help here's my code.
You can delete all Firebase related imports from app.module.ts since this solution only uses Firebase.
The packages rxfire and #angular/fire can be removed from your package.json. The only dependency I have is "firebase": "^9.6.1".
I used observables for the getObject and list functions since that's what I'm used to and I didn't want to rewrite my original code.
import { Injectable } from '#angular/core';
import { Capacitor } from '#capacitor/core';
import { environment } from '#environment';
import { initializeApp } from 'firebase/app';
import { Auth, getAuth, indexedDBLocalPersistence, initializeAuth, signInWithCustomToken } from 'firebase/auth';
import { Database, getDatabase, onValue, orderByChild, query, ref } from 'firebase/database';
import { Observable, Observer, from } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class FirebaseService {
private readonly database: Database;
private readonly auth: Auth;
constructor() {
const firebaseApp = initializeApp(environment.firebase);
if (Capacitor.isNativePlatform()) {
initializeAuth(firebaseApp, {
persistence: indexedDBLocalPersistence
});
}
this.database = getDatabase(firebaseApp);
this.auth = getAuth(firebaseApp);
}
connectFirebase(firebaseToken) {
return from(signInWithCustomToken(this.auth, firebaseToken));
}
disconnectFirebase() {
return from(this.auth.signOut());
}
getObject<T>(path: string): Observable<T> {
return new Observable((observer: Observer<T>) => {
const dbRef = ref(this.database, path);
const listener = onValue(dbRef, snapshot => {
const data = snapshot.val();
observer.next(data);
});
return {
unsubscribe() {
listener();
}
};
});
}
public list<T>(path: string, orderChildBy?: string): Observable<Array<T>> {
return new Observable<Array<T>>((observer: Observer<Array<T>>) => {
const dbRef = ref(this.database, path);
const dbReference = !orderChildBy ? dbRef : query(dbRef, orderByChild(orderChildBy));
const listener = onValue(dbReference, snapshot => {
const data = Object.values<T>(snapshot.val() || {});
console.log(path, data);
observer.next(data);
});
return {
unsubscribe() {
listener();
}
};
});
}
}
For those who can't see the error message thrown by firebase try the following command in your Safari console to see the error.
window.location.reload()
Try to downgrade your angularfire to v7.0 it might work with firebase v9.
in my case i folow this link: https://github.com/angular/angularfire/issues/3087#issuecomment-990599459
I was also having this issue when building for an iOS emulator and actual iOS device, but adding this to the app.component.ts worked for me.
import { Component } from '#angular/core';
import { Capacitor } from '#capacitor/core';
import { initializeApp } from 'firebase/app';
import { indexedDBLocalPersistence, initializeAuth } from 'firebase/auth';
import { environment } from 'src/environments/environment';
#Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.scss'],
})
export class AppComponent {
constructor() {
const app = initializeApp(environment.firebase);
if (Capacitor.isNativePlatform) {
initializeAuth(app, {
persistence: indexedDBLocalPersistence
});
}
}
}
This is where I found the fix and a sample code

Angular 12 Material shows cannot read property errorstate undefined of MatFormField

This is the simple HTML that I have written for single page web app
<div class="bg">
<h1 class="faq_heading">Frequently Asked Questions</h1>
<div class="search">
<mat-form-field class="search_input">
<input type="text" placeholder="Search" class="search_input" matInput [(ngModel)]="inp" (keyup)="onKey($event)" />
</mat-form-field>
<mat-form-field>
<mat-label>Categories</mat-label>
<mat-select class="dropdown" placeholder="Categories">
<mat-option value="Default">Default</mat-option>
</mat-select>
</mat-form-field>
<img src="../assets/images/search.svg" alt="" class="search_img" />
</div>
</div>
There is nothing much in the component.ts file just the basic template and required import statements
Following is the app.module.ts
import { NgModule } from "#angular/core";
import { BrowserModule } from "#angular/platform-browser";
import { MatFormFieldModule } from "#angular/material/form-field";
import { AppRoutingModule } from "./app-routing.module";
import { AppComponent } from "./app.component";
import { MatGridListModule } from "#angular/material/grid-list";
import { MatSelectModule } from "#angular/material/select";
import { MatPaginatorModule } from "#angular/material/paginator";
import { MatDialogModule } from "#angular/material/dialog";
import { MatSnackBarModule } from "#angular/material/snack-bar";
import { BrowserAnimationsModule } from "#angular/platform-browser/animations";
import { HttpClientModule } from "#angular/common/http";
import { faqservice } from "./faq.service";
import { MatExpansionModule } from "#angular/material/expansion";
import { FormsModule } from "#angular/forms";
#NgModule({
declarations: [AppComponent],
imports: [
FormsModule,
MatExpansionModule,
HttpClientModule,
BrowserModule,
AppRoutingModule,
MatFormFieldModule,
MatGridListModule,
MatSelectModule,
MatDialogModule,
BrowserAnimationsModule,
MatSnackBarModule,
MatPaginatorModule,
],
providers: [faqservice],
bootstrap: [AppComponent],
})
export class AppModule {}
Following are the errors
Error1:
ERROR TypeError: Cannot read property 'controlType' of undefined
at MatFormField.ngAfterContentInit (form-field.js:527)
at callHook (core.js:2526)
at callHooks (core.js:2495)
at executeInitAndCheckHooks (core.js:2446)
at refreshView (core.js:9486)
at refreshComponent (core.js:10616)
at refreshChildComponents (core.js:9242)
at refreshView (core.js:9495)
at renderComponentOrTemplate (core.js:9559)
at tickRootContext (core.js:10790)
Error2:
ERROR TypeError: Cannot read property 'errorState' of undefined
at MatFormField_HostBindings (form-field.js:830)
at processHostBindingOpCodes (core.js:9213)
at refreshView (core.js:9491)
at refreshComponent (core.js:10616)
at refreshChildComponents (core.js:9242)
at refreshView (core.js:9495)
at renderComponentOrTemplate (core.js:9559)
at tickRootContext (core.js:10790)
at detectChangesInRootView (core.js:10815)
at RootViewRef.detectChanges (core.js:22865)
As you can see there is not much in the code as I have just started the development , but I am already getting errors in basic templates direct from the docs.
How to handle these errors?
(please note that I am new to angular material, if possible just mention some details around the answer)
Here is the package.json
{
"name": "faq1",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test"
},
"private": true,
"dependencies": {
"#angular/animations": "~12.1.1",
"#angular/cdk": "^12.1.1",
"#angular/common": "~12.1.1",
"#angular/compiler": "~12.1.1",
"#angular/core": "~12.1.1",
"#angular/forms": "~12.1.1",
"#angular/material": "^12.1.1",
"#angular/platform-browser": "~12.1.1",
"#angular/platform-browser-dynamic": "~12.1.1",
"#angular/router": "~12.1.1",
"rxjs": "~6.6.0",
"tslib": "^2.2.0",
"zone.js": "~0.11.4"
},
"devDependencies": {
"#angular-devkit/build-angular": "~12.1.1",
"#angular/cli": "~12.1.1",
"#angular/compiler-cli": "~12.1.1",
"#types/jasmine": "~3.6.0",
"#types/node": "^12.11.1",
"jasmine-core": "~3.7.0",
"karma": "~6.3.0",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage": "~2.0.3",
"karma-jasmine": "~4.0.0",
"karma-jasmine-html-reporter": "^1.5.0",
"typescript": "~4.3.2"
}
}
Import and declare the MatInputModule in the module file solve the issue
....
import {MatInputModule} from '#angular/material/input';
#NgModule({
...
,
imports: [
...
MatInputModule,
],
providers: [
....
]
})
export class MyModule {}
I hade same problem, but when changed to this, issue fixed:
<mat-form-field appearance="fill">
<mat-label>Status</mat-label>
<mat-select>
<mat-option *ngFor="let status of ['active', 'inactive']" [value]="status">
{{status}}
</mat-option>
</mat-select>
</mat-form-field>
I had the same problem, but I solved it adding an ngIf in the mat-form-field tag.
<mat-form-field appearance="fill" *ngIf="role$ | async as roles">
<mat-label>Select a role</mat-label>
<mat-select formControlName="codeRole">
<mat-option *ngFor="let r of roles" [value]="r.code>
{{r.description}}</mat-option>
</mat-select>
</mat-form-field>

Using #ngrx/Effect an effect is not being triggered by an Action

I expect that the Effect that I created should be triggered by dispatching an action, but it is not happening.
The action is being dispatched correctly, but the effect seems that is not properly watching this.
I created this effect:
import { Injectable } from '#angular/core';
import { Actions, Effect, ofType } from '#ngrx/effects';
import { Action } from '#ngrx/store';
import { Observable, of } from 'rxjs';
import { map, mergeMap, catchError } from 'rxjs/operators';
import { PoliciesService } from 'app/services/policies';
import * as policiesActions from '../actions/policies.actions';
import { Policy } from 'app/dtos/policy.dto';
import { PoliciesMapper } from 'app/services/policies/policies.mapper';
Injectable();
export class PoliciesEffect {
constructor(
private actions$: Actions,
private policyService: PoliciesService
) { }
#Effect()
getPolicies$: Observable<Action> = this.actions$.pipe(
ofType<policiesActions.GetPoliciesAction>(
policiesActions.ActionPoliciesType.GET_POLICIES
),
mergeMap((actions: policiesActions.GetPoliciesAction) =>
this.policyService.getPolicies().pipe(
map((policies: Policy[]) =>
new policiesActions.GetPoliciesActionSuccess(PoliciesMapper.policiesCollectionToPoliciesModelCollection(policies))
),
catchError(err => of(new policiesActions.GetPoliciesActionFailed(err)))
)
)
);
}
This effect expect to be triggered once the Action GetPoliciesAction is being dispatch.
This is not happening so I am not able to do the HTTP request to get my data from the server.
Here are the Actions that I created using #ngrx/store:
import { Action } from '#ngrx/store';
import { Policy } from 'app/dtos/policy.dto';
import { PolicyModel } from 'app/models/policy.model';
export enum ActionPoliciesType {
GET_POLICIES = '[Policies] Get all policies list',
GET_POLICIES_SUCCESS = '[Policies] Policies received succesfully',
GET_POLICIES_FAILED = '[Policies] Policies reception failed'
}
export class GetPoliciesAction implements Action {
readonly type = ActionPoliciesType.GET_POLICIES;
constructor() { }
}
export class GetPoliciesActionSuccess implements Action {
readonly type = ActionPoliciesType.GET_POLICIES_SUCCESS;
constructor(public payload: PolicyModel[]) { }
}
export class GetPoliciesActionFailed implements Action {
readonly type = ActionPoliciesType.GET_POLICIES_FAILED;
constructor(public payload: string) { }
}
export type PoliciesActions =
GetPoliciesAction |
GetPoliciesActionSuccess |
GetPoliciesActionFailed;
And here is my app.module.ts:
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { MaterialModule } from './material';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NavbarComponent } from './components/navbar/navbar.component';
import { FooterComponent } from './components/footer/footer.component';
import { HomeComponent } from './components/home/home.component';
import { AngularFireModule } from 'angularfire2';
import { AngularFireDatabaseModule } from 'angularfire2/database';
import { StoreModule } from '#ngrx/store';
import { environment } from '../environments/environment';
import { IPoliciesService } from './services/policies/policies.interface';
import { PoliciesService } from './services/policies';
import { reducers } from './redux/reducers/reducers';
import { StoreDevtoolsModule } from '#ngrx/store-devtools';
import { EffectsModule, Actions} from '#ngrx/effects';
import { HttpClientModule} from '#angular/common/http';
#NgModule({
declarations: [
AppComponent,
NavbarComponent,
FooterComponent,
HomeComponent
],
imports: [
BrowserModule,
AppRoutingModule,
MaterialModule,
AngularFireModule.initializeApp(environment.firebase),
AngularFireDatabaseModule,
StoreModule.forRoot(reducers),
StoreDevtoolsModule.instrument(),
EffectsModule.forRoot([]),
HttpClientModule
],
providers: [{
provide: IPoliciesService,
useClass: PoliciesService
}],
bootstrap: [AppComponent]
})
export class AppModule { }
package.json:
"dependencies": {
"#angular/animations": "^7.0.4",
"#angular/cdk": "^7.3.0",
"#angular/common": "~7.0.0",
"#angular/compiler": "~7.0.0",
"#angular/core": "~7.0.0",
"#angular/forms": "~7.0.0",
"#angular/http": "~7.0.0",
"#angular/material": "^7.3.0",
"#angular/platform-browser": "~7.0.0",
"#angular/platform-browser-dynamic": "~7.0.0",
"#angular/router": "~7.0.0",
"#ngrx/effects": "^7.2.0",
"#ngrx/store": "^7.2.0",
"#ngrx/store-devtools": "^7.2.0",
"angularfire2": "^5.1.1",
"concurrently": "^4.1.0",
"core-js": "^2.5.4",
"firebase": "^5.8.1",
"hammerjs": "^2.0.8",
"rxjs": "~6.3.3",
"zone.js": "~0.8.26"
},
"devDependencies": {
"#angular-devkit/build-angular": "~0.10.0",
"#angular/cli": "~7.0.3",
"#angular/compiler-cli": "~7.0.0",
"#angular/language-service": "~7.0.0",
"#types/node": "~8.9.4",
"#types/jasmine": "~2.8.8",
"#types/jasminewd2": "~2.0.3",
"codelyzer": "~4.5.0",
"jasmine-core": "~2.99.1",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~3.0.0",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "~2.0.1",
"karma-jasmine": "~1.1.2",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "~5.4.0",
"ts-node": "~7.0.0",
"tslint": "~5.11.0",
"typescript": "~3.1.1"
}
You are not providing your effects class to the effects module. In your ngModule import for EffectsModule you are passing an empty array. Your PoliciesEffects service should be in that array.

Why does http request failed to load resource when using Angular in localhost?

I have an ASP.NET MVC project which uses ASP.NET WebAPI along with Angular for UI components. I'm fairly new to Angular so please bear with me. Below are the config files inside my project.
package.json file
{
"name": "angular-quickstart",
"version": "1.0.0",
"description": "QuickStart package.json from the documentation, supplemented with testing support",
"scripts": {
"build": "tsc -p src/",
"build:watch": "tsc -p src/ -w",
"build:e2e": "tsc -p e2e/",
"serve": "lite-server -c=bs-config.json",
"serve:e2e": "lite-server -c=bs-config.e2e.json",
"prestart": "npm run build",
"start": "concurrently \"npm run build:watch\" \"npm run serve\"",
"pree2e": "npm run build:e2e",
"e2e": "concurrently \"npm run serve:e2e\" \"npm run protractor\" --kill-others --success first",
"preprotractor": "webdriver-manager update",
"protractor": "protractor protractor.config.js",
"pretest": "npm run build",
"test": "concurrently \"npm run build:watch\" \"karma start karma.conf.js\"",
"pretest:once": "npm run build",
"test:once": "karma start karma.conf.js --single-run",
"lint": "tslint ./src/**/*.ts -t verbose"
},
"keywords": [],
"author": "",
"license": "MIT",
"dependencies": {
"#angular/common": "~4.3.4",
"#angular/compiler": "~4.3.4",
"#angular/core": "~4.3.4",
"#angular/forms": "~4.3.4",
"#angular/http": "~4.3.4",
"#angular/platform-browser": "~4.3.4",
"#angular/platform-browser-dynamic": "~4.3.4",
"#angular/router": "~4.3.4",
"angular-in-memory-web-api": "~0.3.0",
"systemjs": "0.19.40",
"core-js": "^2.4.1",
"rxjs": "5.0.1",
"zone.js": "^0.8.4"
},
"devDependencies": {
"concurrently": "^3.2.0",
"lite-server": "^2.2.2",
"typescript": "~2.1.0",
"canonical-path": "0.0.2",
"tslint": "^3.15.1",
"lodash": "^4.16.4",
"jasmine-core": "~2.4.1",
"karma": "^1.3.0",
"karma-chrome-launcher": "^2.0.0",
"karma-cli": "^1.0.1",
"karma-jasmine": "^1.0.2",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "~4.0.14",
"rimraf": "^2.5.4",
"#types/node": "^6.0.46",
"#types/jasmine": "2.5.36"
},
"repository": {}
}
systemjs.config.js file
/**
* System configuration for Angular samples
* Adjust as necessary for your application needs.
*/
(function (global) {
System.config({
//baseURL: '/',
paths: {
// paths serve as alias
'npm:': 'node_modules/'
},
// map tells the System loader where to look for things
map: {
// our app is within the app folder
'app': 'app',
// angular bundles
'#angular/core': 'npm:#angular/core/bundles/core.umd.js',
'#angular/common': 'npm:#angular/common/bundles/common.umd.js',
'#angular/compiler': 'npm:#angular/compiler/bundles/compiler.umd.js',
'#angular/platform-browser': 'npm:#angular/platform-browser/bundles/platform-browser.umd.js',
'#angular/platform-browser-dynamic': 'npm:#angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
'#angular/http': 'npm:#angular/http/bundles/http.umd.js',
'#angular/router': 'npm:#angular/router/bundles/router.umd.js',
'#angular/forms': 'npm:#angular/forms/bundles/forms.umd.js',
// other libraries
'rxjs': 'npm:rxjs',
'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js'
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
app: {
main: './main.js',
defaultExtension: 'js'
//meta: {
// './*.js': {
// loader: 'systemjs-angular-loader.js'
// }
//},
},
rxjs: {
defaultExtension: 'js'
}
}
});
})(this);
main.ts file
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
import { enableProdMode } from '#angular/core';
import { AppModule } from './app.module';
// Enable production mode unless running locally
//if (!/localhost/.test(document.location.host)) {
// enableProdMode();
//}
platformBrowserDynamic().bootstrapModule(AppModule);
app.routing.ts file
import { ModuleWithProviders } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { HomeComponent } from './Components/home.component';
const appRoutes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent }
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
app.module.ts file
import { NgModule } from '#angular/core';
import { APP_BASE_HREF } from '#angular/common';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import { AppComponent } from './app.component';
import { routing } from './app.routing';
import { HomeComponent } from './Components/home.component';
import { ChangeService } from './Services/changes.service';
#NgModule({
imports: [BrowserModule, FormsModule, ReactiveFormsModule, HttpModule, routing],
declarations: [AppComponent, HomeComponent],
providers: [{ provide: APP_BASE_HREF, useValue: '/' }, ChangeService],
bootstrap: [AppComponent]
})
export class AppModule {}
changes.service.ts file
import { Injectable } from '#angular/core';
import { Http, Response, Headers, RequestOptions } from '#angular/http';
#Injectable()
export class ChangeService {
constructor(private _http: Http) { }
get(url: string) {
return this._http.get(url);
}
}
app.component.ts file
import { Component, ElementRef, OnInit } from '#angular/core';
import { ChangeService } from './Services/changes.service';
#Component({
selector: 'moc-landing',
templateUrl: './app/Components/home.component.html',
styleUrls: ['./app/Components/home.component.css']
})
export class AppComponent implements OnInit {
maintitle: string;
statusList: IStatus[];
showByList: IShowBy[];
msg: string;
constructor(private elementRef: ElementRef, private _changeService: ChangeService) {
this.maintitle = this.elementRef.nativeElement.getAttribute('maintitle');
}
ngOnInit() {
this.LoadStatus();
this.LoadShowBy();
}
LoadStatus(): void {
this._changeService.get('http://localhost:56534/api/MoC/GetStatuses').subscribe(response => { this.statusList = response.json(); });
}
LoadShowBy(): void {
this._changeService.get('http://localhost:56534/api/MoC/GetShows').subscribe(response => { this.showByList = response.json(); });
}
}
Also in my WebApiConfig.cs, inside static Register method, I also update routeTemplate as below.
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
My issue is that, when I run the application from Visual Studio 2017 on http://localhost:5653; I get Failed to load resource: the server responded with a status of 400 (Bad Request)
When I looked at the browser's console, this is what I got,
I test the http request directly in my browser's address bar http://localhost:56534/api/MoC/GetStatuses, and it gives me the json data that I need. So, there's no problem in WebAPI side.
I found this SO post and, tried to follow Praveen M answer but it didn't worked for me.
Why did I get (400) bad request?, Did I miss an important configuration in my app.routing.ts?
Please, anyone here with a kind heart can spare me a coin?
Try changing:
providers: [{ provide: APP_BASE_HREF, useValue: '/' }, ChangeService]
to just:
providers: [ChangeService]
Well, after banging my head on the wall. I found the culprit of the issue. It's a stupid mistake of mine. The issue isn't on the http request neither related to my localhost. It was one of the component metadata templateUrl. I have mistakenly declare it like this templateUrl: '<span>Hello</span>' instead of just template: '<span>Hello</span>'
That's why the application throws exception because the component template is in bad form http://localhost:56534/%0A%20%20%20%20

Angular Zone Errors in ASP.NET MVC Application

I'm attempting to merge an angular and MVC application together. I'm just trying it on a blank MVC app for beginning purposes by following instructions from a course on pluralsight. However, I'm getting the following error in the console when I try to use the my app tags to test the functionality.
Pricing:56 Error: (SystemJS) XHR error (404 Not Found) loading
http://localhost:5794/src/app/app.module Error: XHR error (404 Not
Found) loading http://localhost:5794/src/app/app.module
at XMLHttpRequest.wrapFn (http://localhost:5794/node_modules/zone.js/dist/zone.js:1166:39)
at ZoneDelegate.invokeTask (http://localhost:5794/node_modules/zone.js/dist/zone.js:425:31)
at Zone.runTask (http://localhost:5794/node_modules/zone.js/dist/zone.js:192:47)
at ZoneTask.invokeTask [as invoke] (http://localhost:5794/node_modules/zone.js/dist/zone.js:499:34)
at invokeTask (http://localhost:5794/node_modules/zone.js/dist/zone.js:1540:14)
at XMLHttpRequest.globalZoneAwareCallback (http://localhost:5794/node_modules/zone.js/dist/zone.js:1566:17)
Error loading http://localhost:57594/src/app/app.module as
"./app/app.module" from http://localhost:57594/src/main.js
at XMLHttpRequest.wrapFn (http://localhost:5794/node_modules/zone.js/dist/zone.js:1166:39)
at ZoneDelegate.invokeTask (http://localhost:5794/node_modules/zone.js/dist/zone.js:425:31)
at Zone.runTask (http://localhost:5794/node_modules/zone.js/dist/zone.js:192:47)
at ZoneTask.invokeTask [as invoke] (http://localhost:5794/node_modules/zone.js/dist/zone.js:499:34)
at invokeTask (http://localhost:5794/node_modules/zone.js/dist/zone.js:1540:14)
at XMLHttpRequest.globalZoneAwareCallback (http://localhost:5794/node_modules/zone.js/dist/zone.js:1566:17)
Error loading http://localhost:5794/src/app/app.module as
"./app/app.module" from http://localhost:5794/src/main.js
Looks like it's obviously related to the zone.js file, but I can't figure this out for the life of me.
systemjs.config.js code:
/**
* System configuration for Angular samples
* Adjust as necessary for your application needs.
*/
(function (global) {
System.config({
paths: {
// paths serve as alias
'npm:': '/node_modules/'
},
// map tells the System loader where to look for things
map: {
// our app is within the app folder
'app': '/app',
// angular bundles
'#angular/core': 'npm:#angular/core/bundles/core.umd.js',
'#angular/common': 'npm:#angular/common/bundles/common.umd.js',
'#angular/compiler': 'npm:#angular/compiler/bundles/compiler.umd.js',
'#angular/platform-browser': 'npm:#angular/platform-browser/bundles/platform-browser.umd.js',
'#angular/platform-browser-dynamic': 'npm:#angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
'#angular/http': 'npm:#angular/http/bundles/http.umd.js',
'#angular/router': 'npm:#angular/router/bundles/router.umd.js',
'#angular/forms': 'npm:#angular/forms/bundles/forms.umd.js',
// other libraries
'rxjs': 'npm:rxjs',
'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js'
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
app: {
main: 'main.js',
defaultExtension: 'js',
meta: {
'./*.js': {
loader: 'systemjs-angular-loader.js'
}
}
},
rxjs: {
defaultExtension: 'js'
}
}
});
})(this);
package.json code:
{
"name": "angular-quickstart",
"version": "1.0.0",
"description": "QuickStart package.json from the documentation, supplemented with testing support",
"scripts": {
"build": "tsc -p src/",
"build:watch": "tsc -p src/ -w",
"build:e2e": "tsc -p e2e/",
"serve": "lite-server -c=bs-config.json",
"serve:e2e": "lite-server -c=bs-config.e2e.json",
"prestart": "npm run build",
"start": "concurrently \"npm run build:watch\" \"npm run serve\"",
"pree2e": "npm run build:e2e",
"e2e": "concurrently \"npm run serve:e2e\" \"npm run protractor\" --kill-others --success first",
"preprotractor": "webdriver-manager update",
"protractor": "protractor protractor.config.js",
"pretest": "npm run build",
"test": "concurrently \"npm run build:watch\" \"karma start karma.conf.js\"",
"pretest:once": "npm run build",
"test:once": "karma start karma.conf.js --single-run",
"lint": "tslint ./src/**/*.ts -t verbose"
},
"keywords": [],
"author": "",
"license": "MIT",
"dependencies": {
"#angular/common": "~4.3.4",
"#angular/compiler": "~4.3.4",
"#angular/core": "~4.3.4",
"#angular/forms": "~4.3.4",
"#angular/http": "~4.3.4",
"#angular/platform-browser": "~4.3.4",
"#angular/platform-browser-dynamic": "~4.3.4",
"#angular/router": "~4.3.4",
"angular-in-memory-web-api": "~0.3.0",
"systemjs": "0.19.40",
"core-js": "^2.4.1",
"rxjs": "5.0.1",
"zone.js": "^0.6.23"
},
"devDependencies": {
"concurrently": "^3.2.0",
"lite-server": "^2.2.2",
"typescript": "~2.1.0",
"canonical-path": "0.0.2",
"tslint": "^3.15.1",
"lodash": "^4.16.4",
"jasmine-core": "~2.4.1",
"karma": "^1.3.0",
"karma-chrome-launcher": "^2.0.0",
"karma-cli": "^1.0.1",
"karma-jasmine": "^1.0.2",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "~4.0.14",
"rimraf": "^2.5.4",
"#types/node": "^6.0.46",
"#types/jasmine": "2.5.36"
},
"repository": {}
}
main.ts code
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
import { AppModule } from './app.module';
platformBrowserDynamic().bootstrapModule(AppModule);
app.module.ts code:
import { NgModule } from '#angular/core';
import { APP_BASE_HREF } from '#angular/common';
import { BrowserModule } from '#angular/platform-browser';
import { ReactiveFormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import { AppComponent } from './app.component';
import { routing } from './app.routing';
import { HomeComponent } from './components/home.component';
#NgModule({
imports: [BrowserModule, ReactiveFormsModule, HttpModule, routing],
declarations: [AppComponent, HomeComponent],
providers: [{ provide: APP_BASE_HREF, useValue: '/' }],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component code:
import { Component } from "#angular/core"
#Component({
selector: "user-app",
template: `
<div>
<nav class='navbar navbar-inverse'>
<div class='container-fluid'>
<ul class='nav navbar-nav'>
<li><a [routerLink]="['home']">Home</a></li>
</ul>
</div>
</nav>
<div class='container'>
<router-outlet></router-outlet>
</div>
</div>
`
})
export class AppComponent {
}
home.component.ts code
import { Component } from "#angular/core";
#Component({
template: `<img src="../../images/users.png" style="text-align:center"/>`
})
export class HomeComponent {
}
Thoughts?

Resources