I am trying to understand what produces the "EXCEPTION: Cannot read property 'url' of undefined" error in a particular instance. I am importing socket.io into the component, and am emitting within my ngOnInit, which is also being correctly imported. I'm also referencing a chat service, which is also being imported and instantiated in the constructor, and provided in the root app.module. The problem is connected to the "url" being referenced within my ngOnInit. This is what I have in the component:
import { Router } from '@angular/router';
import { AlertService } from './data/alert.service';
import { Component, ViewContainerRef, OnInit } from '@angular/core';
import * as io from 'socket.io-client';
import './rxjs-operators';
import { API } from "./data/api.service";
import { Search } from "./data/search.service";
import { ChatService } from './ui/chat/chat.service';
@Component({
selector: 'app',
templateUrl: 'app/app.component.html',
styleUrls: ['app/app.component.css']
})
export class AppComponent implements OnInit
{
private socket;
private routeUrl;
private url: string;
public tabOptions: string[] = ['typeA/', 'typeB/'];
public static get view(): ViewContainerRef
{
return AppComponent._view;
}
private static _view: ViewContainerRef;
constructor(api: API,
search: Search,
viewContainer: ViewContainerRef,
private router: Router,
private chatService: ChatService)
{
AppComponent._view = viewContainer;
}
ngOnInit() {
this.router.events.subscribe((route) => {
let routeUrl = route.url;
console.log('The user route changed to: ' + routeUrl);
this.chatService.trackUser();
});
}
}
This component is calling on a chat.service, and specifically a "trackUser()" function, which looks like this:
import { ContextMenu } from './../context-menu.component';
import { AuthenticationService } from './../../data/authentication.service';
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';
import * as io from 'socket.io-client';
import { Http } from '@angular/http';
@Injectable()
export class ChatService {
private url = 'http://localhost:5000';
private socket;
name;
nickname;
user;
message;
routeUrl;
route;
constructor(private http: Http,
private authenticationService: AuthenticationService) {}
trackUser() {
let routeUrl = this.route.url;
this.socket.emit('track-user', this.routeUrl);
}
sendMessage(message) {
this.socket.emit('add-message', message);
console.log(message);
}
getMessages() {
let observable = new Observable(observer => {
this.socket = io(this.url);
this.socket.on('message', (data) => {
observer.next(data);
});
return () => {
this.socket.disconnect();
};
});
return observable;
}
}
What I have tried:
I have tried using the code provided above, but am getting the error described above that I'm trying to track.