500 when calling setTitle using angular 2 titleService and server side rendering - javascript

I have a problem with server side rendering using angular 2 and titleService.
My code looks like this
import { Component } from '#angular/core';
import { BrowserModule, Title } from '#angular/platform-browser';
import { Router } from '#angular/router';
#Component({
selector: 'app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [Title]
})
export class AppComponent {
constructor(private titleService: Title) {
titleService.setTitle("Setting the title...");
}
}
This works fine using client side rendering but when reloading the page I get this error:
Exception: Call to Node module failed with error: TypeError: Cannot create property 'title' on string ''
Any ideas why this occurs?

With angular universal there should be no need to provide any external service as this is built in. (as echonax stated in the comments.)
Working example with this angular-universal fork. I guess it should be the same for your version of angular-universal.
app.component.ts
import { Component, OnInit } from '#angular/core';
import { Router, NavigationEnd } from '#angular/router';
import { Meta, Title } from '#angular/platform-browser';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
constructor(private _router: Router, private _meta: Meta, private _title: Title) { }
ngOnInit() {
this._router.events.subscribe((event) => {
if (event instanceof NavigationEnd) {
switch (event.urlAfterRedirects) {
case '/':
this._title.setTitle('title goes here');
this._meta.updateTag({ name: 'description', content: 'same goes for meta content' });
break;
case '/another-route':
this._title.setTitle('Another title');
this._meta.updateTag({ name: 'description', content: 'You get the idea' });
break;
}
}
});
}
}
NavigationEnd takes care of setting a new title each time I navigate to a new route.
Hope it helps.

I guess this might be expected since the titleService interacts with element only present in the browser. When reading the "Universal Gotchas" it clearly status that you need to check if you are on the client or in the browser when doing this. I expected the titleService to handle such things though. However checking if client solved the problem.
Se: https://github.com/angular/universal

Related

getting ExpressionChangedAfterItHasBeenCheckedError Angular 4

Im aware similar questions exist but none of those have provided me with an answer that works..
Basically I have a site with some services that inject data dynamically
In my app.component.ts I have two headers.. one when your on the home page and one for when your on any other page
app.component.html
<app-header *ngIf="router.url !== '/'"></app-header>
<app-header-home *ngIf="router.url != '/'"></app-header-home>
<router-outlet></router-outlet>
<app-footer></app-footer>
app.component.ts
import { Component } from '#angular/core';
import { Router } from '#angular/router';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'app';
router: string;
constructor(
private _router: Router
) {
this.router = _router.url;
}
}
now I also have a service that dynamically injects the title of the header
headerTitle.service.ts
import { Injectable } from '#angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
#Injectable()
export class HeaderTitleService {
title = new BehaviorSubject('');
constructor() { }
setTitle(title: any) {
this.title.next(title);
}
}
then In my home component for example I set the title
home.component.ts
import { Component, OnInit, AfterViewInit } from '#angular/core';
import { HeaderTitleService } from '../../services/headerTitle.service';
import { HeaderImageService } from '../../services/headerImage.service';
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
constructor(
private headerTitleService: HeaderTitleService,
private headerImageService: HeaderImageService
) { }
ngOnInit() {
}
ngAfterViewInit() {
this.headerTitleService.setTitle(`
We strive to create things
<br> that are engaging, progressive
<br> & above all
<span class="highlight">
<em>innovative.</em>
</span>
`);
}
}
now basically it was all working until I put in the if statements on the two headers
now Im getting this error
Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: ''. Current value: '
We strive to create things
<br> that are engaging, progressive
<br> & above all
<span class="highlight">
<em>innovative.</em>
</span>
'.
not sure how I can fix this.. I tried setting the values in ngAfterViewInit but it did nothing
or does anyone know another way I could accomplish this??
Thanks
You can try using a setTimeOut method instead and set the values
inside of that
setTimeout(this.headerTitleService.setTitle(`
We strive to create things
<br> that are engaging, progressive
<br> & above all
<span class="highlight">
<em>innovative.</em>
</span>
`), 0);
note this is a work around and not a full proff solution to the problem .
To know why this error occurs in Angular change detection you need to know how the change detection works in Angular for this you can refer to this blog by Maxim NgWizard K
I know i fixed this in mine.
here is a great post
everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror
i have forced the change detection
export class AppComponent {
name = 'I am A component';
text = 'A message for the child component';
constructor(private cd: ChangeDetectorRef) {
}
ngAfterViewInit() {
this.cd.detectChanges();
}

Confusing behavior of a BehaviorSubject in my Angular App

I recently ran into a problem and can't really figure out what's wrong with my code at this point, hopefully someone of you can help me.
All I am trying to do is changing the value of my BehaviorSubject with a function but it isn't working out.
chat.service.ts
import { Injectable } from '#angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
#Injectable()
export class ChatService {
chatId = new BehaviorSubject<number>(0);
constructor() {
this.chatId.next(1);
}
changeChatId(chatId: number) {
console.log(chatId);
this.chatId.next(chatId);
}
}
So the subscribers get the default as well as the changed chatId from the constructor. But as soon as I try to change it with the changeChatId function nothing happens at all. The right id's get passed into the function I already debugged that but the line this.chatId.next(chatId) doesn't seem to do anything.
ADD
These are the other components the service is currently used in.
chat-message-list
import { Component, OnInit, Input} from '#angular/core';
import { ChatService } from "../../../shared/services/chat.service";
#Component({
selector: 'app-chat-message-list',
templateUrl: './chat-message-list.component.html',
styleUrls: ['./chat-message-list.component.css'],
providers: [ChatService]
})
export class ChatMessageListComponent implements OnInit {
chatId: number;
constructor(private chat: ChatService) { }
ngOnInit() {
this.chat.chatId.subscribe(
chatId => this.updateMessageList(chatId)
);
}
}
chat-item
import { Component, OnInit, Input} from '#angular/core';
import { User } from '../../../shared/models/user.model';
import { ChatService } from '../../../shared/services/chat.service';
#Component({
selector: 'app-chat-list-item',
templateUrl: './chat-list-item.component.html',
styleUrls: ['./chat-list-item.component.css'],
providers: [ChatService]
})
export class ChatListItemComponent implements OnInit {
#Input()
user: User;
constructor(private chat: ChatService) { }
ngOnInit() {
}
onChatItemSelected(){
this.chat.changeChatId(this.user.id);
}
}
You need to make your ChatService a singleton (shared) service. Add it to the providers of your ngModule. This allows all the components that use the ChatService to share the same service instance.
#NgModule({
providers: [ChatService]
})
And remove it from your components providers. When you are adding it to your components providers, that component gets its own instance of ChatService which can not be used by other components.

How to send data from one component to another using a shared service

I wanted to send data using subject to another component (for a earning purpose). I am not able to fetch back the data. Here is my code:
app.component.ts
import { Component } from '#angular/core';
import { shareService } from './share.service';
#Component({
selector: 'my-app',
template: `
<hello></hello>
<button (click)="passData()">
Start
</button>
`,
styleUrls: [ './app.component.css' ],
providers:[shareService]
})
export class AppComponent {
constructor(private service : shareService){}
passData(){
this.service.send("hello");
}
}
hello.component.ts
import { Component, Input } from '#angular/core';
import { shareService } from './share.service';
import { Subscription } from 'rxjs/Subscription';
#Component({
selector: 'hello',
template: `<h1>Hello!</h1>`,
styles: [`h1 { font-family: Lato; }`],
providers:[shareService]
})
export class HelloComponent {
subscription: Subscription;
constructor(private share : shareService){
this.subscription = share.subj$.subscribe(val=>{
console.log(val);
})
}
}
share.service.ts
import { Injectable } from '#angular/core';
import { Subject } from 'rxjs/Subject';
#Injectable()
export class shareService{
private sub = new Subject();
subj$ = this.sub.asObservable();
send(value: string) {
this.sub.next(value);
}
}
I am not getting the value in console.
Here is the working Demo : DEMO
By putting:
#Component({
.....
providers: [sharedService]
})
in both components, you are creating two distinct instances of the shared service.
Each instance is not 'aware' of the data from each component.
Provide it at module level and create a singleton service:
#NgModule({
....
providers: [sharedService]
})
This way, you inject the service as a single instance in the both components, so they can share it as they will share the data.
Or using the Angular's preferred new way :
Beginning with Angular 6.0, the preferred way to create a singleton
service is to specify on the service that it should be provided in the
application root. This is done by setting providedIn to root on the
service's #Injectable decorator:
#Injectable({
providedIn: 'root',
})
Demo
See also
I dont know why sub$ is used but you dont need that
// just push data to subject. you can use BehavourSubject to initiatte a value.
#Injectable()
export class shareService{
private sub = new Subject();
confirmMission(astronaut: string) {
this.sub.next(astronaut);
}
}
And then in your 2nd component sub scribe it
#Component({
selector: 'hello',
template: `<h1>Hello!</h1>`,
styles: [`h1 { font-family: Lato; }`],
providers:[shareService] // this can be shared in module lebel or componenet level
})
export class HelloComponent {
subscription: Subscription;
constructor(private share : shareService){
this.subscription = share.subj.subscribe(val=>{
console.log(val);
})
}
}
make sure to provide your service in module level or provide it in both the component.

Application Insights does not track unhandled browser exceptions in Angular app

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.

Angular 2 modify view html after processing

I have below angular 2 code
import { Component } from '#angular/core';
#Component({
selector: 'app-root',
template: 'Waiting on port ',
})
export class AppComponent {
}
As an example I would like to append text "3000" to the template output dynamically. How can this be achieved?
So, final output must be "Waiting on port 3000"
EDIT: I should have been a bit more specific. I was expecting answer something like a response object where I could modify the html before it is sent to "frontend" rendering. So, Angular 2 would process binding all the details in the template and then I get the modify the html.
#Component({
selector: 'app-root',
template: 'Waiting on port {{port}}',
})
export class AppComponent {
port:number;
someMethod() {
this.port = 3000;
}
}
Further to Günter Zöchbauer's answer, if you wanted the method to fire when the component's initialized you could use ngOnInit as your method, "called after data-bound properties of a directive are initialized" (from the docs).
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-root',
template: 'Waiting on port {{port}}',
})
export class AppComponent implements OnInit {
port:number;
ngOnInit(): void {
this.port = 3000;
};
}
OnInit must be included in your import.

Categories