我不确定自己是不是完全错误,但是我正在尝试将这些数据分配给变量,以便可以在父类中使用它。这是角度6中的服务。这是整个服务的代码。
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返回数据流,因此我试图将数据分配给变量,并在我的其他应用程序中使用它。
答案 0 :(得分:0)
您可以简单地做到:
// Subscribe to ROS data
const myData = this.data;
driveControlListener.subscribe((message) => {
myData = message;
});
答案 1 :(得分:0)
您可以通过使用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();
}
因此,对于要在应用程序中使用data变量的每个位置,只需订阅即可。示例:
this.rosLibService.getData().subscribe(data => {
console.log(data);
});
您可以在rxjs官方文档中了解有关主题的更多信息,希望对您有所帮助