我有一个关于以Angular 传递数据的问题.

首先,我没有<parent><child [data]=parent.data></child></parent>的 struct

我的 struct 是

<container>
  <navbar>
    <summary></summary>
    <child-summary><child-summary>
  </navbar>
  <content></content>
</container>

所以,在<summary />中,我有一个 Select ,它会将值发送到<child-summary /><content />.

OnSelect方法在<summary />个组件内部进行了良好的激发(更改).

所以,我try 使用@Input@Output@EventEmitter指令,但我不知道如何将事件检索为组件的@Input,除非使用父/子模式.我发现的所有例子都与组件有关.

编辑:BehaviorSubject不工作的示例(所有连接到API的服务都工作正常,只有observable在启动时被触发,但在select值发生更改时不触发)

共享服务=公司.服务ts(用于检索公司数据)

import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class SrvCompany {

    private accountsNumber = new BehaviorSubject<string[]>([]);
    currentAccountsNumber = this.accountsNumber.asObservable();

    changeMessage(accountsNumber: string[]) {
        this.accountsNumber.next(accountsNumber);
    }

    private _companyUrl = 'api/tiers/';

    constructor(private http: Http) { }

    getSociete(): Promise<Response> {
        let url = this._companyUrl;
        return this.http.get(url).toPromise();
    }
}

发票组成部分ts("子元素")

import { Component, OnInit, Input } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';

import { SrvInvoice } from './invoice.service';
import { SrvCompany } from '../company/company.service';

@Component({
    selector: 'invoice',
    templateUrl: 'tsScripts/invoice/invoice.html',
    providers: [SrvInvoice, SrvCompany]
})

export class InvoiceComponent implements OnInit  {

    invoice: any;

    constructor(private srvInvoice: SrvInvoice, private srvCompany: SrvCompany)
    {

    }

    ngOnInit(): void {
        //this.getInvoice("F001");

        // Invoice data is linked to accounts number from company.
        this.srvCompany.currentAccountsNumber.subscribe(accountsNumber => {
            console.log(accountsNumber);
            if (accountsNumber.length > 0) {
                this.srvInvoice.getInvoice(accountsNumber).then(data => this.invoice = data.json());
            }
        });
    }

    //getInvoice(id: any) {
    //    this.srvInvoice.getInvoice(id).then(data => this.invoice = data.json());
    //}
}

公司组成部分ts(触发"父")

import { Component, Inject, OnInit, Input } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';

import { SrvCompany } from './company.service';

@Component({
    selector: 'company',
    templateUrl: 'tsScripts/company/company.html',
    providers: [SrvCompany]    
})

export class CompanyComponent implements OnInit {

    societes: any[];    
    soc: Response[]; // debug purpose
    selectedSociete: any;

    ville: any;
    ref: any;
    cp: any;
    accountNumber: any[];

    constructor(private srvSociete: SrvCompany)
    {

    }

    ngOnInit(): void {
        this.getSocietes();
    }

    getSocietes(): void {

        this.srvSociete.getSociete()
            .then(data => this.societes = data.json())
            .then(data => this.selectItem(this.societes[0].Id));
    }

    selectItem(value: any) {
        this.selectedSociete = this.societes.filter((item: any) => item.Id === value)[0];
        this.cp = this.selectedSociete.CodePostal;
        this.ville = this.selectedSociete.Ville;
        this.ref = this.selectedSociete.Id;
        this.accountNumber = this.selectedSociete.Accounts;
        console.log(this.accountNumber);
        this.srvSociete.changeMessage(this.accountNumber);
    }
}

推荐答案

在这种情况下,您希望使用共享服务,因为您的组件是以sibling 和孙辈的形式构建的.下面是一段视频中的一个例子,我制作了一段关于sharing data between components的视频,正好解决了这个问题.

首先在服务中创建一个BehaviorSubject

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class DataService {

  private messageSource = new BehaviorSubject("default message");
  currentMessage = this.messageSource.asObservable();

  constructor() { }

  changeMessage(message: string) {
    this.messageSource.next(message)
  }

}

然后将该服务注入每个组件,并订阅可观察到的服务.

import { Component, OnInit } from '@angular/core';
import { DataService } from "../data.service";
@Component({
  selector: 'app-parent',
  template: `
    {{message}}
  `,
  styleUrls: ['./sibling.component.css']
})
export class ParentComponent implements OnInit {

  message:string;

  constructor(private data: DataService) { }

  ngOnInit() {
    this.data.currentMessage.subscribe(message => this.message = message)
  }

}

您可以更改任一组件的值,该值将被更新,即使您没有父/子关系.

import { Component, OnInit } from '@angular/core';
import { DataService } from "../data.service";
@Component({
  selector: 'app-sibling',
  template: `
    {{message}}
    <button (click)="newMessage()">New Message</button>
  `,
  styleUrls: ['./sibling.component.css']
})
export class SiblingComponent implements OnInit {

  message:string;

  constructor(private data: DataService) { }

  ngOnInit() {
    this.data.currentMessage.subscribe(message => this.message = message)
  }

  newMessage() {
    this.data.changeMessage("Hello from Sibling")
  }

}

Typescript相关问答推荐

React Router SR:useLocate()只能在路由组件的上下文中使用

替换类型脚本类型中的多个特定字符串

如何将http上下文附加到angular中翻译模块发送的请求

如何使用Generics保留构造函数的类型信息?

TypeScript泛型参数抛出错误—?&#"' 39;预期"

如何修复正在处理类型但与函数一起使用时不处理的类型脚本类型

扩展函数签名中的参数类型,而不使用泛型

泛型类型联合将参数转换为Never

TypeScrip界面属性依赖于以前的属性-针对多种可能情况的简明解决方案

通过按键数组拾取对象的关键点

如何将定义模型(在Vue 3.4中)用于输入以外的其他用途

声明文件中的类型继承

vue-tsc失败,错误引用项目可能无法禁用vue项目上的emit

TypeScrip错误:为循环中的对象属性赋值

类型脚本-处理值或返回值的函数

如何从接口中省略接口

如何扩展RxJS?

如何静态键入返回数组1到n的函数

如何使用useSearchParams保持状态

对象只能使用 Typescript 中另一个对象的键