我不确定我是否做错了,但是我试图将这些数据分配给一个变量,这样我就可以在父类中使用它了。这是一个角度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正在返回一个数据流,所以我尝试将该数据分配给一个变量,并在我的应用程序的其余部分中使用它。
发布于 2018-10-23 01:31:53
你可以通过使用主题来实现这一点。只需将变量数据作为类型主题。示例:
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官方文档中了解更多有关主题的信息,希望这会有所帮助。
发布于 2018-10-23 00:37:36
你可以简单地做:
// Subscribe to ROS data
const myData = this.data;
driveControlListener.subscribe((message) => {
myData = message;
});https://stackoverflow.com/questions/52939461
复制相似问题