I've already read similar questions regarding this on StackOverflow, but they don't seem to be working for my situation. I'm on the most recent version of Angular.
Loader Component
import {Component, ElementRef, OnInit, OnDestroy} from '#angular/core';
import {CORE_DIRECTIVES} from "#angular/common";
import {LoadingService} from "../../services/global/loadingService";
#Component({
selector: 'loader',
directives: [CORE_DIRECTIVES],
providers: [LoadingService],
template: `
<div class ="blue"></div>
`,
})
export class LoadingComponent {
public active: boolean;
public constructor(spinner: LoadingService) {
spinner.status.subscribe((status: boolean) => {
this.active = status;
});
}
}
Loader Service
import {Injectable} from '#angular/core';
import {Subject} from 'rxjs/Subject';
import 'rxjs/add/operator/share';
#Injectable()
export class LoadingService {
public status: Subject<any> = new Subject();
private _active: boolean = false;
public get active(): boolean {
return this._active;
}
public set active(v: boolean) {
this._active = v;
this.status.next(v);
}
public start(): void {
this.active = true;
}
public stop(): void {
this.active = false;
}
}
My error is: Error: Uncaught (in promise): No provider for LoadingService!
Any help would be greatly appreciated. Thank you!
There is nothing wrong with the code you posted here. I put it in my project and it loads without any issues. Your issue is most likely your SystemJS configuration or some other issue that prevents the app from loading correctly, and therefore can't resolve how to inject your LoadingService. Use Chrome's dev tools to look at the console when the app loads and see if it shows you any other issues. Alternatively, post your full non-working sample somewhere we can actually see all the code (like Plunkr, or JSFiddle).
I faced a similar issue and solved it by importing the service in the providers specified in app.module.ts
Related
I am working on an Angular 11 application.
In the service UserService I have:
import { Injectable, OnDestroy } from '#angular/core';
import { UserModel } from '../path/to/UserModel';
export class UserService implements OnDestroy {
public isActiveUser: boolean = false;
public checkUserStatus(user: UserModel) {
return this.isActiveUser;
}
}
I use the above service in a component, like this:
import { UserService } from '../path/to/user-service.service';
export class UserComponent implements OnInit {
public isActiveUser: boolean;
public checkUserStatus() {
this.isActiveUser = this.UserService.checkUserStatus(user);
}
}
The problem
In the above CompositionEvent, on the line this.isActiveUser = this.UserService.checkUserStatus(user) I get the error:
Cannot find name 'user'
What causes this error?
The user variable is missing in your code.
Here are scenarios to set the user variable
import { UserService } from '../path/to/user-service.service';
// Import your model with below path
import { UserModel } from '../path/to/UserModel';
export class UserComponent implements OnInit {
public isActiveUser: boolean;
// Declare your user variable
user: UserModel;
public checkUserStatus() {
this.isActiveUser = this.UserService.checkUserStatus(user);
}
}
Resolve your error :)
In the above CompositionEvent, on the line this.isActiveUser = this.UserService.checkUserStatus(user) I get the error:
Coz no user constant / variable is declared.
Because your user variable is never defined anywhere?
I am facing circular dependency warning in my current project. I need some help to fix this warning issue. I have searched StackOverflow or tech blogs to fix this issue. Unfortunately, I am ending with no proper solution. It will greater if someone helps me with this.
Below is the project folder structure.
src
app
services
slice
slice.service.ts
slices
home
help
help.component.html
help.component.ts
home.module.ts
index.ts
WARNING in Circular dependency detected:
src\app\slices\home\help\help.component.ts -> src\app\services\slice\slice.service.ts ->
src\app\slices\index.ts -> src\app\slices\home\help\help.component.ts
help.component.ts
import { ChangeDetectionStrategy, Component, OnInit } from '#angular/core'
import { select, Store } from '#ngrx/store'
import { Observable } from 'rxjs'
// components
import { BaseSliceComponent } from '#app/components/slice/base-slice.class'
// services
import { SliceService } from '#app/services/slice/slice.service'
// models
import { SliceOptions } from '#app/models/slice/slice.model'
// selectors
import config from './store/victims.selector'
#Component({
selector: 'app-help',
templateUrl: './help.component.html',
styleUrls: ['./help.component.scss'],
})
export class HelpComponent extends BaseSliceComponent implements OnInit {
config: Observable<SliceOptions> = this.store.pipe(select(config))
constructor(private store: Store<any>, private sliceService: SliceService) {
super()
}
ngOnInit(): void {}
}
slice.service.ts
import {
ComponentRef,
Injectable,
ViewContainerRef
} from '#angular/core'
import { Router } from '#angular/router'
import { Store } from '#ngrx/store'
import SliceMap from '#app/slices'
import { SliceNameKeys } from '#app/models/slice/slice.model'
#Injectable({
providedIn: 'root'
})
export class SliceService {
private sliceStack: ComponentRef<any>[] = []
private sliceHost!: ViewContainerRef
constructor(
private store: Store<any>,
private router: Router,
) { }
create(
name: SliceNameKeys,
id?: string | undefined,
shouldClear?: boolean,
index?: number
) {
id = id ?? name // if no id specified keep name as id
const slice = SliceMap[name]
}
}
slices/index.ts
import { SliceNames } from '#app/models/slice/slice.model'
// components
import { AboutUsComponent } from './home/aboutus/aboutus.component'
import { HelpComponent } from './home/help/help.component'
const SliceMap: SliceNames = {
help: HelpComponent,
aboutUs: AboutUsComponent
}
export default SliceMap
base-slice.class.ts
export abstract class BaseSliceComponent {
id = ''
}
There is no right solution or tool that can find circulation dependency automatically in your project.
You just need to carefully check each service and injectable that is not circularly dependent.
Like
A->B and B->A
You need to check-in each service dependency as well.
I'm experiencing an issue with the Microsoft Application Insights SDK for JavaScript that was closed/fixed awhile ago: https://github.com/Microsoft/ApplicationInsights-JS/issues/282
I created a brand new Angular app using the Angular CLI. Then I made these changes, following this article.
Added a monitoring service:
import {Injectable} from '#angular/core';
import {AppInsights} from 'applicationinsights-js';
#Injectable()
export class MonitoringService {
private config: Microsoft.ApplicationInsights.IConfig = {
instrumentationKey: 'KEY_GOES_HERE',
enableDebug: true,
verboseLogging: true
};
constructor() {
if (!AppInsights.config) {
AppInsights.downloadAndSetup(this.config);
}
}
logPageView(name?: string, url?: string, properties?: any, measurements?: any, duration?: number) {
AppInsights.trackPageView(name, url, properties, measurements, duration);
}
logEvent(name: string, properties?: any, measurements?: any) {
AppInsights.trackEvent(name, properties, measurements);
}
trackException(exception: Error) {
AppInsights.trackException(exception);
}
}
Added it to my app.component.ts:
import {Component, OnInit} from '#angular/core';
import {MonitoringService} from './monitoring.service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [MonitoringService]
})
export class AppComponent implements OnInit {
title = 'app works!';
constructor(private monitoringService: MonitoringService) { }
ngOnInit() {
this.monitoringService.logPageView();
}
throwAnException() {
this.monitoringService.trackException(new Error('manually track exception'));
throw 'this should appear in app insights'; // but it doesn't
}
}
Made a simple button for throwing the exception in my app.component.html:
<h1>
{{title}}
</h1>
<div (click)="throwAnException()">Click to throw an exception</div>
Logging a page view works, as does tracking the exception by explicitly calling trackException. From reading the documentation and various articles, I was under the impression that uncaught exceptions would always automatically get sent to Application Insights. However, I am not seeing any of those show up in the portal.
What could I be missing here?
Using these versions:
applicationinsights-js: 1.0.11
#types/applicationinsights-js: 1.0.4
I've struggles with the same thing and here is the things you need to know to hack it through:
What is happenning?
Angular catches all the exceptions (swallows them!) and just logs them inside console. I have not seen this behavior being explicitly told in any documentation, but I've tested this in code, so trust me. On the other hand only uncaught exceptions are autocollected! (see here). For collecting caught exceptions ( as is mostly the case when using angular framework) you have to call trackException() explicitly in your code.
How to solve it :
We will implement a service (called MonitoringService in code below) to communicate with azure application insights. Then we will tell angular to use this service to log exceptions in azure ai, instead of logging just into browser console, by extending ErrorHandler class.
1) implement MonitoringService:
We'll be using a service named MonitoringService to communicate with azure application insights. Implement that service like this:
import { Injectable } from "#angular/core";
import { ApplicationInsights } from "#microsoft/applicationinsights-web";
import { environment } from "#env/environment";
#Injectable({
providedIn: "root",
})
export class MonitoringService {
private appInsights: ApplicationInsights;
constructor() {}
startMonitoring(): void {
this.appInsights = new ApplicationInsights({
config: {
instrumentationKey: environment.appInsights.instrumentationKey,
},
});
this.appInsights.loadAppInsights();
this.appInsights.trackPageView();
}
logException(exception: Error, severityLevel?: number) {
this.appInsights.trackException({
exception: exception,
severityLevel: severityLevel,
});
}
}
startMonitoring() should be called on app start up.
2) start monitoring on app start up:
Angular projects mostly have a app.component.ts file which belongs to the root module and is bootstrapped/initialized as the first component. By the term "on app start up", I actually mean the time this component is being initialized.
We'll create an instance of MonitoringService and have it start its job:
import { Component } from '#angular/core';
import { MonitoringService } from 'services/monitoring.service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent {
constructor(
private monitoringService: MonitoringService
) {
this.monitoringService.startMonitoring();
}
}
3) Log errors into application insights, before they are swallowed by framework:
Extend ErrorHandler class in your project. This class is actually a hook for centralized exception handling in angular spa. Use this hook, to log exceptions before they are swallowed by framework:
import { Injectable, ErrorHandler } from '#angular/core';
import { MonitoringService } from './monitoring.service';
#Injectable({
providedIn: 'root'
})
export class GlobalErrorHandlerService implements ErrorHandler {
constructor(private monitoringService: MonitoringService) { }
handleError(error: any): void {
console.error(error);
this.monitoringService.logException(error);
}
}
4) Register the ErrorHandler with Angular:
In the AppModule make sure to register this Handler with Angular:
#NgModule({
providers: [{provide: ErrorHandler, useClass: GlobalErrorHandlerService}]
})
class AppModule {}
I don't think AppInsights has any knowledge of Angular and the other way around, Angular doesn't know about app insights so you'll probably have to add this in by yourself using a custom ErrorHandler. Have a look at the ErrorHandler official documentation. If you put your this.monitoringService.trackException call in the handleError there it should work fine.
I want to import js file in typescript.
And I want to access object and function in the js files.
Also I added js file in index.html but It doesn't working too.
so I find a clue that "import '[js file path]'" but it doesn't working.
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { NavParams } from 'ionic-angular';
import '../../pages/mobile.js';
#Component({
selector: 'page-success',
templateUrl: 'success.html'
})
export class SuccessPage {
constructor(public navCtrl: NavController, public navParms: NavParams) {
let centerPos = new atlan.maps.UTMK(953933.75, 1952050.75);
}
}
This is success.ts file. I want to find 'atlan' object.
Give me a solution please. Thx a lot!
You have to use the declare keyword so you do not get any compilation errors. You can do the following
import { Component } from '#angular/core';
....
/* Here you are telling typescript compiler to
ignore this variable it did not originate with typescript.*/
declare var atlan: any;
#Component({
selector: 'page-success',
templateUrl: 'success.html'
})
export class SuccessPage {
....
}
In your file ../../pages/mobile.js, you must export your atlan object (if you can edit this file of course), then, you import it the same way you do with everything.
I tried everything and I cannot get an http request to go out to my node server on heroku. I can hit the route manually so its not the server. I will paste my service and my page.
**Class is subscription.service.ts
import {Http, Response} from '#angular/http'
import {Injectable} from '#angular/core'
import 'rxjs/add/operator/map';
#Injectable()
export class SubscriptionService {
http:Http;
constructor(http:Http){
this.http = http;
}
getEntries() {
return this.http.get('my url here *****').map(res => res.json());
}
}
**Class is dashboard.component.ts
import {Component, ViewEncapsulation} from '#angular/core';
import {SubscriptionService} from '../../_services/subscription.service';
import 'rxjs/Rx';
#Component({
selector: 'dashboard',
providers: [SubscriptionService],
encapsulation: ViewEncapsulation.None,
styles: [require('./dashboard.scss')],
template: require('./dashboard.html')
})
export class Dashboard {
getData: string;
constructor(private subscriptionService: SubscriptionService) {
}
ngOnInit() {
console.log("test!!");
this.subscriptionService.getEntries()
.subscribe(data => this.getData = JSON.stringify(data),
error => console.log("Error!"),
() => console.log("finished!")
);
}
}
My ngOnInit() is being called, I see the console print, but no request shows up in logs on heroku. Also no errors show up in console.
Make sure you have imported the HttpModule in root.
I don't see anything else which can cause this. For make sure http is working you can put a break point in SubscriptionService on getEntries method and follow where it leads you.
Update:- as pointed out by #peeskillet there is nothing wrong with your dependency. try to debug and update your question with more information.