角度9:不订阅其他组件吗?

时间:2020-04-25 03:46:09

标签: angular web-applications observable subscription angular9

我一直在尝试制作一个有角度的应用程序,该应用程序从表单的提交数据中读取并查询数据库。我一直在使用Observables并订阅,但是它一直没有工作。我一直在尝试console.log在表单提交时观察到的数据,但是它似乎没有改变。这是代码。

服务

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

@Injectable()
export class ForSubmitService {
  private subject = new Subject<QueryData>();
  sendData(data: QueryData) {
    this.subject.next(data);
  }
  getData(): Observable<QueryData> {
    return this.subject.asObservable();
  }
}

发送数据的组件

@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.css'],
  providers: [ForSubmitService]
})

constructor(
    private formBuilder: FormBuilder,
    private submitService: ForSubmitService
  ) {
    this.form = this.formBuilder.group({
      selectedHemisphere: '',
      selectedMonth: this.thisMonth,
      }
    );
  }

  ngOnInit(): void {
  }

  onSubmit(formData) {
    const sendData = {northSelected: formData.selectedHemisphere === 'north',
      monthSelected: formData.selectedMonth};
    const data = new QueryData(sendData.northSelected, sendData.monthSelected);
    this.submitService.sendData(data); // This is the line sending the data
  }

接收数据的组件

@Component({
  selector: 'app-fish-list',
  templateUrl: './fish-list.component.html',
  styleUrls: ['./fish-list.component.css'],
  providers: [ForSubmitService]
})

export class ListComponent implements OnInit {
  listData;
  formData;
  subscription: Subscription;
  constructor(
    private db: AngularFirestore,
    private submitService: ForSubmitService ) {
    this.subscription = this.submitService.getData().subscribe(data => {console.log(data); this.formData = data; });
    // ^^^ This is the code that seems to not work
    console.log(this.formData);
    // console.log(this.subscription);
    // More database related code...
  }

  ngOnInit(): void {
  }

任何帮助将不胜感激。谢谢!!

1 个答案:

答案 0 :(得分:1)

当前,每个组件都在看到自己的ForSubmitService实例。 这是因为组件中的这一行:

 providers: [ForSubmitService]

如果ForSubmitService对于您的应用程序是全局的,则更改@Injectable装饰器,使其如此:

@Injectable({
  providedIn: 'root',
})

详细了解提供者:Angular - Providing dependencies in modules