0

Суть такова: имею MainComponent, code:

import {Component, OnInit, OnDestroy, ViewChild, AfterViewInit} from "@angular/core";
import {WebSocketService} from "../services/websocket.service";
import {ActivatedRoute} from '@angular/router';
import {Subscription} from "rxjs/Rx";
import {User} from "../../client/user.model";
import {NotificationComponent} from "../../notification/components/notification.component";
import {ToasterService, ToasterContainerComponent} from "angular2-toaster/angular2-toaster";

@Component({
    selector: 'main',
    template: `<toaster-container></toaster-container>
<notification-component></notification-component>
<button (click)="popToast()">pop toast</button>`,
    providers: [WebSocketService, ToasterService],
    directives: [NotificationComponent, ToasterContainerComponent]
})
export class MainComponent implements OnInit, OnDestroy, AfterViewInit {

    @ViewChild(NotificationComponent) private notification: NotificationComponent;

    private sub: Subscription;
    private user: User;
    private toasterService: ToasterService;

    constructor(private route: ActivatedRoute,
                private ws: WebSocketService,
                toasterService: ToasterService) {
        this.toasterService = toasterService;
        this.user = new User();
    }

    popToast() {
        this.toasterService.pop('success', 'Args Title', 'Args Body');
        this.notification.start({
            timeout: 50,
            type: 'info',
            title: 'Test Web Service',
            body: 1,
            buttonCloseShow: false
        });
    }

    ngOnInit() {}

    ngAfterViewInit() {
        this.sub = this.route
            .params
            .subscribe(params => {
                this.user.room = params['room'];
                this.user.name = params['name'];
                this.user.lastname = params['lastname'];
            });

        this.init();
    }

    init() {
        this.ws = new WebSocketService();
        this.ws.run(this.onMessage);

        setTimeout(() =>
            this.ws.send({
                name: this.user.name,
                lastname: this.user.lastname,
                room: this.user.room,
                action: 'client_go_test'
            }), 500);
    }

    ngOnDestroy() {
        this.sub.unsubscribe();
    }

    onMessage(event: MessageEvent) {
        let routes: Object = {
            'go_test': (response) => {
                console.log(response)
            },
            'client_test_not_found': (response) => {
                //this.toasterService.pop('success', 'Args Title', 'Args Body');
                console.log(this.notification);
                this.notification.start({
                    type: 'info',
                    title: 'Test Web Service',
                    body: response,
                    buttonCloseShow: false
                });
            }
        };

        let data = JSON.parse(event.data);

        if (routes.hasOwnProperty(data.action)) {
            routes[data.action](data.response);
        }
    }
}

NotificationComponent code

import {Component} from "@angular/core";
import {TimerService} from "../services/timer.service";

@Component({
    selector: 'notification-component',
    template: `<div class="j-toast {{toastConfig.type}}" [ngStyle]="{'opacity': opacity}" (mouseenter)="onEnter()" (mouseleave)="onLeave()">
       <div *ngIf="toastConfig.buttonCloseShow" class="toast-close" (click)="close()">X</div>
    <div id="toast-progress" class="toast-progress" [ngStyle]="{'width': timerService.getWidth() + '%'}"></div>
    <div class="toast-content">
        <div class="toast-data">
            <div class="toast-title">{{toastConfig.title}}</div>
            <div class="toast-body">{{toastConfig.body}}</div>
        </div>
        <div class="toast-icon"></div>
    </div>
</div>`,
    providers: [TimerService]
})
export class NotificationComponent {

    private opacity: number = 0;
    public toastConfig: Object = {};

    constructor(public timerService: TimerService) {}

    public start(config: Object) {
        this.opacity = 1;
        this.toastConfig = config;
        this.timerService.start(this.toastConfig['timeout']);
    }

    public close() {
        this.opacity = 0;
        this.timerService.close();
    }

    onEnter(): void {
        this.timerService.pause();
    }

    onLeave(): void {
        this.timerService.resume();
    }
}

когда я вызываю popToast нажатием на кнопку все toast работают, а вот если у меня приходит сообщение от сокетов (проблема не в сокетах) и я там вызываю

this.notification.start({
                    type: 'info',
                    title: 'Test Web Service',
                    body: response,
                    buttonCloseShow: false
                });

то получаю TypeError: Cannot read property 'start' of undefined

1 ответ 1

1

Такая конструкция:

let x = new MyObject();
let y = x.printThing;
y()

теряет контекст this.

Это можно обойти двумя способами:

При передаче метода класса в качестве callback-функции создать дополнительное замыкание:

let y = () => x.printThing()

Или создать это замыкание сразу вместо метода класса:

class MyObject{
private status = "blah";
    public printThing = () => { // <-- 
        alert(this.status);
    }
}

...

let x = new MyObject();
let y = x.printThing
7
  • typescript эту проблему решает, я даже проверил, все тоже
    – jashka
    21 июл 2016 в 4:11
  • а чему вообще равен this в момент когда приходит сообщение от сокетов?
    – Alexandr
    21 июл 2016 в 5:17
  • посмотрите эту статью github.com/Microsoft/TypeScript/wiki/… с момента Red Flags for this. У вас ситуация очень похожа. Попробуйте объявить onMessage так как показано далее в блоке Fixes
    – Alexandr
    21 июл 2016 в 5:25
  • я понял в чем соль, onMessage же callback вебсокетов this указывает на него даже как вы предлагали, как в этом случае быть ? сделать notification статическим ?
    – jashka
    21 июл 2016 в 5:25
  • @jashka см. комментарий выше
    – Alexandr
    21 июл 2016 в 5:26

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.