for some reason I have been getting this error here and can't understand why. I have the array initialized, which is the reason for this error 99% of the time. I have both tried to initialize it with private dashboardConversations: ChatDashboard[] = []
and the way you see below.
profile.component.ts
import { DashboardService } from '../../../pages/chatdashboard/_modules/dashboard.service';
export class ProfileComponent implements OnInit {
private dashboardService: DashboardService;
@Input() public contact: Contact;
public constructor(dashboardService: DashboardService) {
this.dashboardService = dashboardService;
}
public ngOnInit(): void {
this.image = this.contact.profilePicture;
this._isAddInfoPresent();
this.dashboardService.createNewConversation(this.contact);
}
}
dashboard.service.ts
export class DashboardService {
private dashboardConversations: ChatDashboard[] = new Array<ChatDashboard>();
private bsDashboardConversations$: BehaviorSubject<ChatDashboard[]> = new BehaviorSubject<ChatDashboard[]>(this.dashboardConversations);
public constructor(){}
public activeConversations$(): Observable<ChatDashboard[]> {
return this.bsDashboardConversations$.asObservable();
}
public createNewConversation(user: Contact): void {
const newUser: ChatDashboard = {
id: user.id,
profilePicture: user.profilePicture,
isImportant: false,
lastMessageReceived: null,
hasUnreadMessages: false,
unreadMessages: null,
};
console.log('user before push', newUser); // all appropriate info is there
this.dashboardConversations.push(newUser); //Error here
}
}
dashboard.page.ts
public conversations$: ChatDashboard[] = [];
private dashboardService: DashboardService;
public constructor( dashboardService: DashboardService){
this.dashboardService = dashboardService;
}
public ngOnInit(): void {
this.dashboardService.activeConversations$().subscribe((conversations: ChatDashboard[]): void => {
this.conversations$ = conversations;
});
}
ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'push' of null
edit: showed more code.
createNewConversation
? That's most likely the faulty code – Poul Kruijtthis
context of the service class. You canconsole.log
the object you want to push, but thethis
is no longer the rightthis
. Sooo, can you post the part where you actually call thecreateNewConversation
method – Poul Kruijt