简体   繁体   中英

calling angular component function from plain javascript

I am using angular for my web app and i need bluetooth on one of my pages. I am using loginov-rocks/bluetooth-terminal( https://github.com/loginov-rocks/bluetooth-terminal ) for the bluetooth connection and it works i can conect my device and see data from it. now the problem i have is i cannot get the data from my recieve function to my angular component, i can print data to console, but that is not what i want, i want to parse my data and set some variables in my angular component from it.Here is my code:

let bluetooth = new BluetoothTerminal();

bluetooth.receive = function (data) {
    console.log(data);
    //i want to call ParseBtData here from my angular component to parse data
    //or somehow send data and cach it for parsing inside my component
};

export class GpsAppComponent extends AppComponentBase implements OnInit
{
//all the angular stuff

    parseBtData(data) {
        //parse my BT data and set some variables inside my component...
    };
}

I have tryed making BluetoothTerminal inside the component, but i still cannot call any function to parse my data. Is it even possible to do that, or is there another way i should aproach my problem?

In general if you create an object javascript you can do it using declare, then the only is override the "received" data. But a change because an event not controlle by Angular, you need say to Angular that "something" has changed outside Angular, so you need use ngZone, some like:

//DISCLAMER: I don't know if work

declare var bluetooth = new BluetoothTerminal();

export class AppComponent implements AfterViewInit
{
   constructor(private ngZone:NgZone,private dataService:DataService){}
   ngAfterViewInit(){
       bluetooth.receive = (data)=> {
           this.ngZone.run(()=>{
              this.dataService.sendData(data)
           })
       };
   }
}

Then you only need define in your service

bluethoodData:Subject<any>=new Subject<any>()
sendData(data:any)
{
   this.bluethoodData.next(data)
}

And you can subscribe in any component to dataService.bluethoodData

   this.dataService.bluethoodData.subscribe(res=>{
       console.log(res)
   })

I managed to solve my problem by moving my bluetooth inside the component and doing:

this.bluetooth.receive = (data) => {
        //console.log(data);
        this.writeToTerminalConsole(data);
    };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM