标签: angular2-observables

订阅方法不会对更改做出反应[Angular 2]

我的app.component中有方法可以更改LangService中的语言.当发生更改时,LangService应该使用Observable对象响应所有其他组件,因为我订阅了所有组件中的更改.不幸的是,它没有发生.它只响应调用该函数来改变语言的app.component.我不确定我在哪里弄错了.也许我只是误解了整个概念,因为我是Angular的新手.

这是代码:

app.component.html

<nav class="navbar navbar-default">
  <div class="container-fluid">
    <div class="navbar-header">
      <a class="navbar-brand" href="#">                                           
        {{ title }}
      </a>
    </div>
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav navbar-right">
        <ol class="breadcrumb">
          <li *ngFor="let lang of langs">
            <a (click)="changeLanguage(lang)">
              {{ lang }}
            </a>  
          </li>
        </ol>
      </ul>
    </div>
  </div>
</nav>
<router-outlet></router-outlet>
Run Code Online (Sandbox Code Playgroud)

app.component.ts

import { Component } from '@angular/core';
import './rxjs-operators';
import { ROUTER_DIRECTIVES } from '@angular/router'; 
import { LangService } from './lang.service';
import { NotesComponent } from './notes/notes.component';

@Component({
  moduleId: module.id,
  selector: 'app-root',
  templateUrl: 'app.component.html', …
Run Code Online (Sandbox Code Playgroud)

angular2-services angular2-observables angular

5
推荐指数
1
解决办法
556
查看次数

Angular2 CanDeactivate with async observable

我正在调查Guards并试图阻止CanDeactivate导航.我想用Save/Cancel显示一个简单的模态,save = navigate and well,cancel = cancel.

我有CanDeactivate工作,但似乎它没有在正确的时间解决

Guard.ts

canDeactivate(component: PortfolioModelComponent) {
    component.saveChanges(); // Opens modal
    return component.modalResponse.take(1); // isnt happening at the right time
}
Run Code Online (Sandbox Code Playgroud)

Component.ts

 public modalResponse: Observable<boolean> = new Observable((observer) => { });

public saveChanges() {
    this.openSaveChangeModal();
}

// Modal save changes
public openSaveChangeModal() {
    $('#savePortfolioChangesModal').modal();
}

public closeSaveChangesModal() {
     this.modalResponse = new Observable((observer) => {
        observer.next(false);
    });
    $('#savePortfolioChangesModal').modal('hide');
}

public saveSaveChangesModal() {
    this.modalResponse = new Observable((observer) => {
        observer.next(true);
    });
    $('#savePortfolioChangesModal').modal('hide');
}
Run Code Online (Sandbox Code Playgroud)

在第一次"保存"时,一旦显示模态,就不会发生任何事情.在第二个"保存",导航将在我回答模态之前发生.如何在合适的时间解决问题?

observable angular-routing angular2-guards angular2-observables angular

5
推荐指数
0
解决办法
1318
查看次数

Angular2 处理非组件类中的订阅

我有一个关于 Angular2 中订阅处理的高级问题。我最近阅读了很多关于糟糕的订阅处理如何由于未正确取消订阅而导致代码中的内存泄漏。

@Components 的一个简单解决方案是满足周围的所有订阅并在 ngOnDestroy 生命周期事件中处理它们。

但是,对于不属于 @Component 并且有订阅的控制器,正确取消订阅的最佳方法是什么?目前,我正在考虑让控制器公开订阅或它自己的 onDestroy 方法,但这并不觉得它可以轻松/通用地完成,所以我很想听听其他选项/意见。

谢谢!

编辑:澄清这不是服务问题,而只是控制器问题。

observable rxjs angular2-observables angular

5
推荐指数
1
解决办法
399
查看次数

angular2 ngFor从ngOnInit()上的api获取数据时不起作用

comment.component.ts:

import { Component, OnInit } from '@angular/core';
import { Router} from '@angular/router'
import { Comment } from 'comment entity path'
import {CommentService} from 'comment service path'
import { Observable } from 'rxjs/Observable';
@Component({
    template: ` <ul><li *ngFor="let comment of comments|async"> {{comment.Name}}</li></ul>`
})
export class CommentComponent implements OnInit {
    comments: Observable<comment[]>;  

    constructor(private router: Router, private commentService: CommentService) {
    }

    ngOnInit() {
        this.comments = this.getComments();
    }

    getComments() {
        return this.commentService.getComments();
    }

}
Run Code Online (Sandbox Code Playgroud)

comment.service.ts

import { Injectable } from '@angular/core';
import { …
Run Code Online (Sandbox Code Playgroud)

angular2-observables angular

5
推荐指数
1
解决办法
7067
查看次数

从组件订阅服务中的 Observable

我已经搜索了很长时间来了解如何订阅一个值不断更新的数组。

我需要了解如何正确设置我的 Angular 2+ 服务 observable 并在我的组件中正确订阅它。请假设代码的所有其他部分都能正常工作。

@Injectable()
export class AutocompleteService {

    searchTerm: string;
    results = [];
    observe$ = Observable.from(this.results);

    searchTest(term){
        this.searchTerm = term.toLowerCase();

        if(this.searchTerm.length > 2){
            this.recruiters.forEach(function(el){
                if(el.name.toLowerCase().indexOf(term) != -1) {
                    this.results.push(el);
                }   
            });    

        }
    }

    getCurrentResults():Observable<Object> {
        return this.observe$;
    }
Run Code Online (Sandbox Code Playgroud)

服务中的一切都按预期工作。如果我登录,term我会从我的组件中获取用户输入。或者results匹配搜索结果后的数组被推送到它上面。

@Component({
    selector: 'autocomplete',
    templateUrl: './autocomplete.component.html',
    providers: [AutocompleteService]
})
export class AutocompleteComponent implements OnInit{
    constructor(private autocompleteService: AutocompleteService){}

    value: string = '';
    searchControl = new FormControl();

    // fired when input happens
    getResults(event){
        this.autocompleteService.searchTest(event.target.value);

        this.autocompleteService.getCurrentResults().subscribe(
            value …
Run Code Online (Sandbox Code Playgroud)

observable angular2-services angular2-observables angular

5
推荐指数
2
解决办法
1万
查看次数

Angular - 表单数组的valueChanges

this.editForm = this.fb.group({
        step1: this.fb.group({
            transport_type_id: ['', [Validators.required]],
            flight_code: ['', []],
        }),
        stops: this.fb.array([
            this.initStop() //adds dynamicaly the fields, but I want to watch the whole array
        ])
    });
Run Code Online (Sandbox Code Playgroud)

如果我想为step1.transporter_id"valueChanges",那么这个observable工作正常

this.editForm.controls.step1.get('flight_code').valueChanges.subscribe(data => {});
Run Code Online (Sandbox Code Playgroud)

如果我想"观察""stops:this.fb.array",语法是什么?

不起作用的例子

this.editForm.controls.stops.get().valueChanges.subscribe(data => {});
this.editForm.controls.stops.get('stops').valueChanges.subscribe(data => {});
this.editForm.get('stops').valueChanges.subscribe(data => {});
Run Code Online (Sandbox Code Playgroud)

angular2-observables angular angular-reactive-forms

5
推荐指数
1
解决办法
1853
查看次数


angular2使用PrimeNG-Scheduler实现FullCalendar-Scheduler

FullCalendar有一个名为Scheduler的附加组件,我试图与PrimeNG-Schedule组件一起使用.查看PrimeNG文档,我可以使用"选项"属性向FullCalendar发送任意信息.这确实有效,但是当我将数据检索连接到异步API时,会导致问题.

API使用Observables然后我在组件中订阅.这适用于事件,因为视图在事件更改时自动更新.

但是,当通过PrimeNG'选项'属性向FullCalendar提供'资源'时,事情不能按预期工作,因为设置'options'属性的代码在API调用有机会返回之前运行,因此空.

我确信这一点,因为如果我对资源进行硬编码,就会有所作为.

我可以想出几种方法来解决这个问题:

  1. 使调用同步(想避免这种情况)

  2. 等待所有数据加载然后(重新)渲染视图(使其与#1几乎相同)

  3. 配置options.resources属性,以便在更改时,视图会更新,就像它对事件一样(这是最好的选择,但不确定它是否可能)

我将不胜感激任何帮助.谢谢.

<p-schedule 
    [events]="events" 
    [businessHours]="businessHours"
    [options]="optionConfig"
    >
</p-schedule>
Run Code Online (Sandbox Code Playgroud)

我的(现在)虚拟API

getEvents() {
    return this.http
    .get('assets/api/mockEvents.json')
    .map((response : Response) => <Appointment[]>response.json().data)
    .catch(this.handleError);
  }

  getResources() {
    return this.http
    .get('assets/api/mockResources.json')
    .map((response : Response) => <Resource[]>response.json().data)
    .catch(this.handleError);
  }
Run Code Online (Sandbox Code Playgroud)

组件文件

ngOnInit() {

  this.schedulerService.getEvents()
      .subscribe(events=> this.events = events);

      this.schedulerService.getResources()
      .subscribe(resources => this.resources = resources);
      // ***** If the following code is uncommented, resources are displayed in Schedule view ****
    // this.resources = [
    //     new Resource(1, "Dr. Hibbert", "blue", true, …
Run Code Online (Sandbox Code Playgroud)

schedule primeng angular2-observables angular

5
推荐指数
1
解决办法
1692
查看次数

使用RxJS获得"不是函数"错误

看似突然之间我得到了RxJS的错误.

我的项目是Angular,Typescript,我使用RxJS作为NGRX redux的一部分.

我的代码似乎完全正常,只是作为导入:

import { Observable } from 'rxjs/Observable'

然后,我从无处开始得到这样的错误......

Uncaught (in promise): TypeError: this.appStateStore.withLatestFrom is not a function Uncaught (in promise): TypeError: this.appStateStore.take is not a function

我能够withLatestFrom通过添加导入来解决错误,import 'rxjs/add/operator/withLatestFrom';但随后错误移动到抱怨.take.

我猜我在某处导入错误,因为我对RxJS了解你需要导入你需要的位.但是我已经检查了我的源代码控制更改,我看不到会导致这种情况刚刚开始发生的任何更改(例如节点模块版本,导入语句).

我做错了什么?

rxjs typescript ngrx angular2-observables angular

5
推荐指数
1
解决办法
4604
查看次数

在IE中的ngOnit()中编写时,observable订阅不起作用

我已经定义了一个行为主题:

component.ts

bsub1: BehaviorSubject<Array<any>> = new BehaviorSubject(null);
Run Code Online (Sandbox Code Playgroud)

并在其上调用next():

HTML:

<button (click) = getData()>Data</button>
Run Code Online (Sandbox Code Playgroud)

component.ts:

getData() {
    getSomething(value, bsub1);
}
Run Code Online (Sandbox Code Playgroud)

service.ts

getSomething(value, _observable) {
    //do something

    _observable.next(retun)
    somevariable.map(p => {
        return { "a": value1, "b": value2 }
    });
}
Run Code Online (Sandbox Code Playgroud)

并订阅:

component.ts

 ngOnInit() {
     bsub1.subscribe(list=>{
         console.log("subscribed to bsub1")
     });
 }
Run Code Online (Sandbox Code Playgroud)

但是在调用getSomething()之后,我的代码没有达到订阅状态.它在组件加载时到达那里,但是在调用next()之后它没有订阅.这只发生在IE 11中,而在edge,chrome和firefox中它正在发挥作用.

有人可以解释我这种行为吗?

behaviorsubject angular2-observables angular5

5
推荐指数
0
解决办法
564
查看次数