为什么会出现“订阅不是函数”错误?

时间:2019-01-02 03:06:26

标签: angular rxjs subscribe

我有一个组件,允许用户从端口列表中选择一个选项。做出选择后,单击“连接端口”按钮。这将调用一项服务来存储所选端口,以便可以将其存储为字符串。

Screenshot of the UI for this step.

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

港口服务

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” 。这样我就可以在整个应用程序中使用它。

1 个答案:

答案 0 :(得分:5)

您的setPort未将端口设置为“可观察”,请尝试将值转换为Observable

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