【问题标题】:Can't get updated value from service variable无法从服务变量中获取更新值
【发布时间】:2021-06-17 05:56:26
【问题描述】:

我正在尝试根据服务变量应用过滤器来搜索项目,该服务变量使用来自该服务的输入进行更新。但我只是从组件中的服务中获取初始值

服务 HTML(我输入的任何内容都会正确分配给变量 searchInput):

<input [value]="searchInput" (keyup)="searchInputChange.next(searchFilterService.applyFilter($event.target.value))">

Service TS(之所以叫组件,是因为我已经有一个同名atm的服务了):

export class SearchFilterComponent {

    searchInput: string = 'test';
    searchInputChange: Subject<string> = new Subject<string>();

    constructor(
        public searchFilterService: SharedSearchFilterService) {
        this.searchInputChange.subscribe((value) => {
            this.searchInput = value
        });
    }

    getSearchInput(): string {
        return this.searchInput;
    }
}

过滤服务 TS

@Injectable()
export class SharedSearchFilterService {
    
    applyFilter(filterValue: string) {

        if (filterValue) return filterValue;
        else return ''; // I need this to avoid getting 'undefined'
    }
}

组件 HTML(这里我得到的初始值是“test”,然后它永远不会从服务中获取新值):

<ng-container *ngIf="searchFilterService.licenceFilter(item, service.getSearchInput())">

示例链接:https://stackblitz.com/edit/angular-buagfs

【问题讨论】:

    标签: angular typescript subject


    【解决方案1】:

    您的示例中的AppService 是一个组件。您必须使用@Output 来通知值。

    app.service.ts

    @Component({
      selector: 'search-component',
      template: `
        <div fxLayout="row" fxLayoutAlign="space-between center">
          <input
            [(ngModel)]="searchInput"
            (keyup)="onKeyUp()"
          />
        </div>
      `
    })
    export class AppService implements OnInit {
      searchInput: string = 'test';
      @Output() inputValue = new EventEmitter<string>();
    
      constructor() {
      }
    
      ngOnInit() {
        this.inputValue.emit(this.searchInput);
      }
    
      onKeyUp(): void {
        this.inputValue.emit(this.searchInput);
      }
    
      getSearchInput(): string {
        return this.searchInput;
      }
    }
    

    app.component.html

    <hello name="{{ name }}"></hello>
    <search-component (inputValue)="onInputValueEmitted($event)"></search-component>
    <div *ngIf="searchInput == 'test'">This shouldn't be seen if value is not 'test'</div>
    

    app.component.ts

    import { Component, OnInit } from '@angular/core';
    import { AppService } from './app.service';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      name = 'Angular';
      searchInput = '';
    
      constructor(private service: AppService) {}
    
      onInputValueEmitted(value: string) {
        this.searchInput = value;
      }
    }
    

    Stackblitz sample

    【讨论】:

    • 完全不同的方法,这个有效。只是好奇:我试图避免声明一个变量来读取组件的输入,这可能吗?
    【解决方案2】:

    您需要将变量this.searchInput 与您传递给函数getSearchInput 的值相等

    //see that the function has an argument
    getSearchInput(searchInput:string): string {
        this.searchInput=searchInput //<--first equal the variable
        return this.searchInput;
      }
    

    顺便说一句,Angular 还没有一种方法可以实现您的目标:FormControl 和 valueChanges

    如果您在 .html 中使用 FormControl

    <input [formControl]="control" />
    

    在您的 .ts 中

    //create a "getter" to access easy to this.control.value
    get searchInput()
    {
      return this.control.value
    }
    set searchInput(value)
    {
       this.control.setValue(value)
    }
    
    control=new FormControl()
    constructor() {
      this.control.valueChanges.subscribe(value => {
          console.log('Prueba de subject: ', value);
      });
    }
    

    【讨论】:

    • 嘿,感谢这个解决方案,但我没有任何东西可以传递给函数,因为一切都在服务中处理
    猜你喜欢
    • 1970-01-01
    • 2021-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-10
    • 2014-12-16
    • 1970-01-01
    • 2015-10-09
    相关资源
    最近更新 更多