从可观察订阅传递变量 Angular 6

Passing variables from an observable subscription Angular 6

我不确定我这样做是否完全错误,但我正在尝试将此数据分配给一个变量,以便我可以在父级中使用它 class。这是 angular6 中的一项服务。这是整个服务的代码。

import {Injectable} from '@angular/core';
import { Observable } from 'rxjs';
import '../assets/roslib.js';

@Injectable({
  providedIn: 'root'
})

export class RoslibService {
  // Creates object with the ROS library
  // @ts-ignore <= Makes ts happy, wont error
    ros = new ROSLIB.Ros({
      // Set listen URL for ROS communication
    url : 'ws://localhost:9090'
  });
  // Data variable to hold ROS data
  data: any = "Not Touched";
  // Initialize function sets everything up, called on a ngOnInit in app.component
  initialize() {
    let data = "UnTouch";
    // Listens for error from ROS and logs it
    this.ros.on('error', function(error) {
      console.log(error);
    });

    // Find out exactly when we made a connection.
    this.ros.on('connection', function() {
      console.log('Connection made!');
    });
    // Logs when connection is closed
    this.ros.on('close', function() {
      console.log('Connection closed.');
    });

    // Get Data from ROS
    // @ts-ignore
      const driveControlListener = new ROSLIB.Topic({
      ros : this.ros, // Points to ROS variable
      name : '/drive_control/parameter_updates', // Topic Name
      messageType : 'dynamic_reconfigure/Config' // Message Type
    });

    // Subscribe to ROS data
     driveControlListener.subscribe((message) => {
      console.log('Recieved Message on ' + driveControlListener.name + ' : ' + message.bools);
      data = message;
      return message;
    });
     this.data = data;
  }

  getDriveControlData(): Observable<any> {
    console.log(this.data);
    return this.data;
  }
  getThrustersState(): Observable<any> {
    console.log("Getting Thruster State");
    console.log(this.data);
    return this.data;
  }
}

driveControlListener 正在返回一个数据流,因此我试图将该数据分配给一个变量并在我的应用程序的其余部分中使用它。

你可以简单地做:

     // Subscribe to ROS data
     const myData = this.data;
     driveControlListener.subscribe((message) => { 
        myData = message;
     });

您可以使用 Subjects 来实现这一点。只需将变量数据设为 Subject 类型。示例:

data: BehaviorSubject<any> = new BehaviorSubject('Untouched');

然后

  // Subscribe to ROS data 

driveControlListener.subscribe((message) => { 
console.log('Recieved Message on ' + driveControlListener.name + ' : ' + message.bools); 
this.data.next(message);
});


// define a getter for data
getData() {
return this.data.asObservable();
}

因此,对于您想要在应用中使用数据变量的每个地方,只需订阅它即可。示例:

this.rosLibService.getData().subscribe(data => {
console.log(data);
});

你可以在 rxjs 官方文档中了解更多关于 Subjects 的知识,希望对你有所帮助