this bound to subscribe function and not outer component scope in Angular2

2024/2/27 9:04:41

I am having an issue in one of my components in Angular2 where as 'this' is bound to wrong context within one of my components. I have other components where this issue is not occurring but I cannot see what the difference is. Here is my code:

Component:

import { Component, Input } from '@angular/core';
import { FilesService } from "./services/files.service";@Component({selector: 'my-app',moduleId: module.id,templateUrl:'/app/views/app.html'
})export class AppComponent {openFileUploader: boolean = false;fileUploaderScope:any;constructor (private _filesService: FilesService) {let self = this;_filesService.emitter.subscribe((response) => {this.fileUploaderScope = response.filters;this.openFileUploader = response.open;},() => {},() => {})}
}

Inside my constructor function you can see I am dependency injecting the filesService then subscribing to an Event Emitter that is returned from this service within the constructor itself with the 'subscribe' function. As you can see from the following lines I am then watching for events and in the callback function I am mapping a response to some local component variables:

_filesService.emitter.subscribe((response) => {this.fileUploaderScope = response.filters;this.openFileUploader = response.open;},

The only problem here is that 'this' is not bound to the correct context. When I add a breakpoint inside that subscribe function it is saying 'this' is not defined. I am using Typescript (ECMA6 functionality) so the arrow function has lexical this binding and is defined in the context of the constructor so 'this' should be bound to the component? As I said I have other components which have the same functionality which have no problems with the 'this' context so I am confused as to why this is happening. Can anyone spot where I have gone wrong?

Thanks

Answer

I haven't seen the pattern that causes the issue in your code, but commonly it's caused by

function () { ... }

instead of

() => { ... }

or when functions are passed around like

     _filesService.emitter.subscribe((response) => {this.fileUploaderScope = response.filters;this.openFileUploader = response.open;},errorHandler,onCompleteHandler}

instead of

     _filesService.emitter.subscribe((response) => {this.fileUploaderScope = response.filters;this.openFileUploader = response.open;},errorHandler.bind(this),onCompleteHandler.bind(this)}

or

     _filesService.emitter.subscribe((response) => {this.fileUploaderScope = response.filters;this.openFileUploader = response.open;},(error) => errorHandler(error),() => onCompleteHandler()}
http://en.ppmy.cn/q/41478.html

Related Q&A

Typescript: Add a function to moment.js namespace

Im trying to add extra functionality to moment.js library. I want to add a function that itself requires a moment() call in its body and Im having a hard time figuring this out.Im using the latest vers…

Display posts on blogger based on Label?

I need to make my homepage to display posts based on a certain label. I dont want all posts to show up at the section of homepage posts. I searched for away on Google Search and I found away that you r…

Nodejs Convert text to JSON

For some reason Im having such a hard time converting this txt file to an actual javascript array.myJson.txt{"action": "key press", "timestamp": 1523783621, "user&quo…

Firebase Auth and Google Calendar

What I am trying to do is use Firebase to authenticate with Google. Then get some data from Google Calendar. I got the first part working. I can authenticate with Google and get user name, email ect., …

Get the file names from multiple file upload field

I am trying to write an ajax uploader using Jquery. In the html I can write a multiple upload field like:<input type=file multiple=multiple name=files[]>But, how can I get the values from this fi…

onmouseover doesnt work when using javascript to add img tag on IE

I need some javascript code that dynamically adds an img tag to a div, and the img tag needs onmouseover and onmouseout handlers.I have it working on Firefox. But it doesnt quite work on IE. On IE, t…

How do you dynamically load a javascript file from different domain?

I find this excellent code, posted by aemkei as answers to this questions:How do you dynamically load a javascript file? (Think C’s #include) Use javascript to inject script references as needed?You…

React FC with forwardedRef

Im facing issue with ref - I need to ref to function component and pass props to it. So far I got my Parent component and Child Component. In my parent component I need to use ref to my child. I need t…

How to find out if ipad is in landscape/portrait mode in javascript/jquery?

I want to add an extra div if the ipad is in landscape mode. Is there some sort of if statement that could find this out?Thanks

Handling the Enter / Return key in Chrome

I have an AJAX-y type page. When the user clicks "GO" I need to execute a specific javascript function. I also want to simulate the "GO" click when a user hits "Enter" or …