export class AppComponent {
title = 'my-app';
constructor(private notifyService : NotificationService) {}
ngOnInit() {
socket.on("laravel_database_chat:test", function(message){
//I WANT TO CALL NOTIFICATION SERVICE HERE, BUT NOT WORKING
this.notifyService.showSuccess();
});
I am trying to call notification service inside socket.io class, but not working.
Change normal function to arrow function to get access to this outside current scope.
ngOnInit() {
socket.on("laravel_database_chat:test", (message) => {
this.notifyService.showSuccess();
});
}
Related
I am using the below code to navigate to parent component on click of "Device Hardware Back Button". I am using Capacitor 3.0 and device backbutton works properly.
Actual issue is that i am not able to access Class members in the callback function.
Below is the code
export class ConfirmBoxComponent extends DialogContentBase implements OnInit{
constructor(public dialog: DialogRef, public myService : MyService) {
super(dialog);
}
ngOnInit(): void {
this.handleHardwareBackButton();
}
public onCancelAction(): void {
console.log("Cancel confirmed", this.dialog)
myService.closeDialog();// closeDialog not available thru arrow or callback functions
}
handleHardwareBackButton(){
App.addListener('backButton',function(){
this.onCancelAction() //not able to access onCancelMethod within callback
})
}
}
Issue is that i am getting "this.onCancelAction" is not a method. Also i tried below code but no use.
handleHardwareBackButton(){
App.addListener('backButton',function(){
this.dialog.close({ actionConfirmed : false }); //here this line doesn't get executed. Also no errors observed
}.bind(this))
}
Am i going wrong somewhere? Please guide me on how to access class members in a callback function?
Try something like this...
export class ConfirmBoxComponent extends DialogContentBase implements OnInit {
constructor(public dialog: DialogRef) {
super(dialog);
}
ngOnInit(): void {
this.handleHardwareBackButton();
}
public onCancelAction(): void {
console.log("Cancel confirmed", this.dialog)
this.dialog.close({ actionConfirmed: false });
}
handleHardwareBackButton() {
App.addListener('backButton', () => {
this.onCancelAction() //not able to access onCancelMethod within callback
})
}
}
I have a sample service:
export class ProjectActionService extends ActionService {
constructor() {
'ngInject'
super($state)
}
getProjects() {
// Call API...
}
}
I would like to change the value of a variable (this.showLoader) that exists in a controller from the getProjects () method.
Controller:
export class ProjectComponent {
constructor() {
'ngInject'
}
$onInit() {
this.showLoader = false
}
}
what is the best way to do it, with a multiple inheritance (mixin), a directive ...?
This is not an appropriate way to deal with it. Your service method should only call the api and get the data and not change controller variables. One way to show/hide loader is changing the boolean before calling and change again after getting the response. A sample inside controller after injecting you service:
this.showLoader = true;
this.ProjectActionService.getProjects().then(response => {
...
})
.finally(() => this.showLoader = false);
I am trying to store the event data from the onRowClicked event in a Component member. So that when the user hits a button it will be deleted. However when I try accessing it from the delete callback the member variable is undefined.
export class OilTypesComponent implements OnInit {
...
selectedOil : any;
gridOptions: GridOptions = <GridOptions>{};
ngOnInit() {
this.gridOptions = {
...
onCellEditingStopped: this.cellEdited,
onRowClicked: this.rowClicked
}
}
...
rowClicked(event){
this.selectedOil = event.data;
}
delete(){
console.log(`Deleting ${this.selectedOil.manufacturer} //this.selectedOil is undefined
}
Turns out it was a scoping issue when passing in the callbacks as shown here:
Angular2 component's "this" is undefined when executing callback function
What I ended up doing for both callbacks
this.gridOptions = {
...
onCellEditingStopped: this.cellEdited.bind(this),
onRowClicked: this.rowClicked.bind(this)
}
I'm learning Angular 2. And got confused over constructor.
Consider the below code :
import { Component, OnInit } from '#angular/core';
import { FormGroup,FormsModule,FormControl } from '#angular/forms';
import { WeatherService } from '../weather.service';
import { WeatherItem } from '../weather-item';
#Component({
selector: 'app-weather-search',
templateUrl: './weather-search.component.html',
styleUrls: ['../../assets/app.css'],
//providers: [WeatherService]
})
export class WeatherSearchComponent implements OnInit {
constructor(private _weatherService : WeatherService) { }
onSubmit(form : FormGroup){
//alert(form.value.location);
this._weatherService.searchWeatherData(form.value.location)
.subscribe(
data => {
const weatherItem = new WeatherItem(data.data.request["0"].query,data.data.weather["0"].maxtempC,data.data.weather["0"].maxtempC);
this._weatherService.addWeatherItems(weatherItem);
console.log(form);
})
}
ngOnInit() {
}
}
Here we are injecting 'WeatherService' in constructor. Can't we do the same outside constructor ? What constructor is doing here actually? Do we really need it here?
The constructor itself is not doing actual work.
Angular creates a new WeatherSearchComponent executing
new WeatherSearchComponent(weatherService);
and this causes the constructor in WeatherSearchComponent to receive the weatherService value.
The constructor
constructor(private _weatherService : WeatherService)
causes an instance field _weatherService to be created and initialized with the value passed from DI.
The constructor is the only place where it is easy to know when the injected service is available and when not.
If the service would passed to a field, setter or method, code in the constructor could not access it because the constructor is executed before outside code has a change to set a field or call a method.
Also for code outside the constructor it is not safe to assume the service is available because this code could be called from the constructor before a field could be set from the outside.
For dependency injection passing dependencies to the constructor is the only way to avoid a lot of complexity.
Dependency Injection in constructor is always better option and while the component is getting created it will get the weatherService as a parameter. To make it clear, below is the transpiled code for your snippet.
var WeatherSearchComponent = (function () {
function WeatherSearchComponent(_weatherService) {
this._weatherService = _weatherService;
}
WeatherSearchComponent.prototype.onSubmit = function (form) {
var _this = this;
//alert(form.value.location);
this._weatherService.searchWeatherData(form.value.location)
.subscribe(function (data) {
var weatherItem = new weather_item_1.WeatherItem(data.data.request["0"].query, data.data.weather["0"].maxtempC, data.data.weather["0"].maxtempC);
_this._weatherService.addWeatherItems(weatherItem);
console.log(form);
});
};
WeatherSearchComponent.prototype.ngOnInit = function () {
};
WeatherSearchComponent = __decorate([
core_1.Component({
selector: 'app-weather-search',
templateUrl: './weather-search.component.html',
styleUrls: ['../../assets/app.css'],
})
], WeatherSearchComponent);
return WeatherSearchComponent;
}());
exports.WeatherSearchComponent = WeatherSearchComponent;
As you can see in turn the javascript code has weatherService Instance being passed on to the function weatherSearchComponent.
in my Angular App i make a simple call to a node.js server. the HttpClient "get"
function returns the right answer. This answer I want to store in a variable of my component "interfaces". But in the "subscribe" function of the get request my "this" pointer doesn't point to my component. Instead it tells me that it is of type "SafeSubscriber". Any call to my member "interfaces" lead to the following error:
TypeError: Cannot read property 'interfaces' of undefined
export class SettingsComponent implements OnInit {
public interfaces : string[];
constructor(private http: HttpClient) {
this.interfaces = [];
this.interfaces.push("huhu");
}
ngOnInit() : void {
this.http.get('http://localhost:3000/settings/interfaces').subscribe((data) => {
// Read the result field from the JSON response.
console.log(data);
this.interfaces.push("xxx");
Object.keys(data).forEach(function(k) {
console.log(k);
this.interfaces.push("xxx");
});
}),
err => {
console.log("error " + err);
};
}
}
As you can see I also tried to enter some values manually into the array just to make sure, that not the server response is causing the problem.
Any help is appreciated.
I used this code as a blueprint which is from:
https://angular.io/guide/http
#Component(...)
export class MyComponent implements OnInit {
results: string[];
// Inject HttpClient into your component or service.
constructor(private http: HttpClient) {}
ngOnInit(): void {
// Make the HTTP request:
this.http.get('/api/items').subscribe(data => {
// Read the result field from the JSON response.
this.results = data['results'];
});
}
}
You're losing reference to the correct this in this statement:
Object.keys(data).forEach(function(k) {..})
Inside the function block code this refers to the calling context , which is the subscribe method itself, that's why interfaces is undefined, since it's not a property of the subscribe method.
You can change the function for a lambda en it should be fine:
Object.keys(data).forEach((k) => {..})