为什么我会收到 "Subscribe is not a function" 错误?

Why am I getting "Subscribe is not a function" error?

我有一个组件允许用户 select 从端口列表中选择一个选项。一旦他们制造了 selection,他们就会点击 "Connect Port" 按钮。这会调用一个服务来存储 selected 端口,以便它可以作为字符串存储。

我收到的控制台日志显示该组件已成功调用服务并按预期进行存储。但是,在任何其他组件中,如果我尝试通过订阅调用该服务;我收到错误。

端口服务

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;
  }
}

应用组件

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);
  }
}

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

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

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