为什么我收到"订阅不是函数"错误?

Cla*_*len 3 subscribe rxjs angular

我有一个组件,允许用户从端口列表中选择一个选项.一旦他们做出选择,他们点击"连接端口"按钮.这会调用服务来存储选定的端口,以便将其存储为字符串.

此步骤的UI屏幕截图.

我正在获取控制台日志,显示组件成功调用服务并按原样存储.但是,在任何其他组件中,如果我尝试使用订阅调用该服务; 我收到错误.

港口服务

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

export interface Port {
  portName: String;
}

@Injectable({
   providedIn: 'root'
})
export class PortService {

activePort;

constructor() { }

setPort(port) {
  console.log('The port: ', port);
  this.activePort = port;
}

getPort(): Observable<Port> {
  console.log('The port for the application runtime: ', this.activePort);
   return this.activePort;
  }
}
Run Code Online (Sandbox Code Playgroud)

应用组件

import { Component, OnInit } from '@angular/core';
import { } from 'electron';
import * as Serialport from 'serialport';
import { SerialService } from './serial.service';
import { PortService, Port } from './core/port.service';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  title = 'electron-angular-serialport';
  collapsed = false;
  connectedPort;

  constructor(private serial: SerialService, private port: PortService) {
    let isElectron: boolean = window && window['process'] && window['process'].type;

    if (isElectron) {
      let serialport: typeof Serialport = window['require']('serialport');
      let app: Electron.App = window['require']('electron').remote;
      console.log(serialport, app, window['process']);
    }
  }

  ngOnInit() {
    this.getPort();
  }

  getPort() {
    console.log('Getting Port');
    this.port.getPort().subscribe( data => this.connectedPort = data);
  }
}
Run Code Online (Sandbox Code Playgroud)

我真的希望我能存储这个字符串"/dev/tty.usbmodem14201".这样我就可以在整个应用程序中使用它.

Fan*_*ung 5

setPort没有将端口设置为Observable,请尝试将值转换为Observable

import {of} from 'rxjs'
...
setPort(port) {
  console.log('The port: ', port);
  this.activePort = of(port);
}
Run Code Online (Sandbox Code Playgroud)

  • 如果你想要一个端口的默认值你可以做(​​(port?port:yourvalue)),也可以设置activePort的默认值来开始activePort = of(null).但实际上这取决于你想如何处理setPort中的空值 (2认同)