从ngOnInit()之外/之内的方法获取变量值

时间:2018-04-03 18:48:23

标签: javascript typescript variables

我正在尝试获取图片(屏幕上的图像)和情感的返回值(点击按钮。即: returnsEmotions )。我想将它们放入makeMatch()函数中,但它们在dashbaord组件中显示为未定义或不显示。我已经尝试在ngOnInit内部和外部使用makeMatch()但仍然没有运气。有什么建议?提前谢谢。

我想要这些的原因是检查图像A何时在屏幕上,如果用户点击情感A /情感B等。

dashboard.component.ts

import {Component,Input,OnChanges,OnInit,SimpleChanges} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {Emotion} from 'emotion';
import {EmotionService} from 'emotion.service';

@Component({
    selector: 'dashboard',
    templateUrl: './dashboard.component.html',
    styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
    emotions: Emotion[] = [];

    constructor(private emotionService: EmotionService) {}

    ngOnInit() {
        this.getEmotions();

        //function to randomize and get face images
        var w = document.getElementById('wrapper');
        var button = document.getElementById('randomize');
        var images = w.children; // inner elements, your image divs
        // a function to hide all divs
        var hideDivs = function(imgs: HTMLCollection) {
            for (var img of < any > imgs) {
                (img as HTMLElement).style.display = 'none';
            } //for
        } //hideDivs

        hideDivs(images); // hide all initially

        button.addEventListener('click', function(event) {
            var rnd = Math.floor(Math.random() * images.length); // get random index
            hideDivs(images); // hide all images

            (images[rnd] as HTMLElement).style.display = 'block'; // show random image
            (event.target as HTMLElement).textContent = 'Click one more time!';
            var getImage = (images[rnd] as HTMLElement);
            console.log('%cImage ID: ', getImage.id);

        }) //button


         //WHERE I WANT TO GET THE IMAGE ONSCREEN AND THE EMOTION BUTTON CLICKED
        var makeMatch = function() {
            console.log('%c In makeMatch method' );
            console.log('%c sE called:', this.submitEmotion);
            console.log('%c gE called:', this.emotionService);
        }

    } //ngOnInitFinishes


    getEmotions(): any {

        this.emotionService.getEmotions().subscribe(emotions => {
            const slice = emotions.slice(0, 9);
            this.emotions = slice;
        });
    } //getEmotionsEnd


    //FUNCTION submitEmotion- returns the emotion selected
    submitEmotion(event, e: string) {

        console.log("%c emotion clicked:", "font-weight: bold", e);
        var returnEmotion = e;
        console.log("%c emotion returned:", "font-weight: bold", returnEmotion);

        return returnEmotion;

    } 


} //end bracket

dashboard.component.html

 //faces
<div id="wrapper" align="center">
    <img class="happy" img src='../../assets/happy.PNG' alt="happy" img id="happy-id"> 
    <img class="sad" img src='../../assets/sad.PNG' alt="sad" img id="sad-id">
    <img class="embarrassed" img src='../../assets/embarrassed.PNG' alt="embarrassed" img id="embarrassed-id">
    <img class="sleepy" img src='../../assets/sleepy.PNG' alt="sleepy" img id="sleepy">
    <img class="stressed" img src='../../assets/stressed.PNG' alt="stressed" img id="stressed">
    <img class="suprised" img src='../../assets/suprised.PNG' alt="suprised" img id="suprised">
    <img class="excited" img src='../../assets/excited.PNG' alt="excited" img id="excited">
 </div>
 <button id='randomize' >START GAME</button>

  //emotions
<div class="grid grid-pad" align="center">
   <a *ngFor="let emotion of emotions" class="col-1-3"  (click)="submitEmotion($event, emotion.name)">
   <div class="module emotion">
      <h4>{{emotion.name}}</h4>
   </div>
   </a>
</div>

enter image description here

1 个答案:

答案 0 :(得分:0)

所以我最终自己找到了这个问题的答案。 我需要在组件中声明两个全局变量。 (emotionMatch + imageMatch)

export class DashboardComponent implements OnInit {
    emotions: Emotion[] = [];
    emotionMatch: string;
    imageMatch: string;
    constructor(private emotionService: EmotionService) {}

FOR INSIDE ngOnInit()

然后我使用this.image在图像的按钮功能中调用imageMatch并将其设置为图像ID。

我还必须使用.bind(this),因为全局变量imageMatch在HTMLElement上不存在。

button.addEventListener('click', function(event) {
    var rnd = Math.floor(Math.random() * images.length); // get random index
    hideDivs(images); // hide all images

    (images[rnd] as HTMLElement).style.display = 'block'; // show random image
    (event.target as HTMLElement).textContent = 'Click one more time!';
    var getImage = (images[rnd] as HTMLElement);

     //update
   this.imageMatch = getImage.id;

    console.log('%cImage ID: ', "font-weight: bold", getImage.id);
    console.log('%c=============================', "color: blue");
    console.log('');

}.bind(this)); //update

FOR OUTSIDE ngInInit()

与inside类似,我只是将全局变量emotionMatch设置为事件e。

submitEmotion(event, e: string) {

        this.emotionMatch = e;
        console.log("%c emotion clicked:", "font-weight: bold", e);
        console.log("%c emotion returned:", "font-weight: bold", this.emotionMatch);


        this.makeMatch();


    } /

     makeMatch() {
        console.log('%c IMAGE CALLED:', "font-weight: bold", this.emotionMatch);
        console.log('%c FACE CALLED:', "font-weight: bold", this.imageMatch );
}

然后在makeMatch()函数中调用它们并成功运行。 希望这有助于某人!