小编Ste*_*eve的帖子

订阅不是函数错误

我试图从服务订阅一个observable,它构建没有错误,但我在浏览器中查看时得到错误"this.service.getBanners(...).subscribe不是一个函数".

服务:

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

@Injectable()

export class BannerService {

    banners: any = ['1','2','3'];

    constructor(
    ) {}

    getBanners(): Observable<any[]> {
        return this.banners;
    }

    setBanners(banners: any[]): void {
        this.banners = banners;
    }

}
Run Code Online (Sandbox Code Playgroud)

零件:

import { Component, ViewEncapsulation, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { BannerService } from './../banner/banner.service';

@Component({
    selector: '.banner',
    templateUrl: './banner.component.html',
    styleUrls: ['./banner.component.sass'],
    encapsulation: ViewEncapsulation.None
})

export class BannerComponent implements OnInit {

    banners: any[]; …
Run Code Online (Sandbox Code Playgroud)

angular-services angular angular-observable

13
推荐指数
2
解决办法
4万
查看次数

[innerHTML]中的Angular routerLink

我一直在寻找一种方法来启用标准的[href]链接,以便在动态加载到[innerHTML]时充当routerLinks.它似乎不是标准的东西,我找不到任何我需要的东西.

我有一个可行的解决方案,但想知道是否有人知道有任何更好的方法来做到这一点或任何潜在的问题,我可能会这样做.

我在app-routing.module.ts中使用jQuery,所以我声明了变量:

declare var $:any;
Run Code Online (Sandbox Code Playgroud)

然后我找到所有具有href属性但没有routerlink属性的锚点.然后我可以获取路径名并告诉路由器在点击时导航到它.

$(document).on('click', `a[href]:not("a[routerlink]"):not("a[href^='mailto:']"):not("a[href^='tel:']")`, function(e){
    if(location.hostname === this.hostname || !this.hostname.length){
        e.preventDefault();
        router.navigate([this.pathname]);
    }
});
Run Code Online (Sandbox Code Playgroud)

这似乎做了这个工作,但我认为必须有一个更"'角度'的方式这样做......

angular angular-router

6
推荐指数
1
解决办法
861
查看次数

Angular 4订阅observable不会在更改后更新

我有一个带有observable的服务,通过组件订阅.当订户显示初始值时,这似乎有效.我有另一个组件,然后更新observable但是新值不会显示.

服务:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of'; 

@Injectable()

export class BannerService {

    banners$: Observable<any[]> = Observable.of([]);

    getBanners(): Observable<any[]> {
        return this.banners$;
    }

    setBanners(banners: any[]): void {
        this.banners$ = Observable.of(banners);
    }

}
Run Code Online (Sandbox Code Playgroud)

订阅者组件:

import { Component, ViewEncapsulation, OnInit } from '@angular/core';

import { BannerService } from './../banner/banner.service';

@Component({
    selector: '.banner',
    templateUrl: './banner.component.html',
    styleUrls: ['./banner.component.sass'],
    encapsulation: ViewEncapsulation.None
})

export class BannerComponent implements OnInit {

    constructor(private bannerService: BannerService){}

    ngOnInit() {
        this.bannerService.banners$.subscribe(banners => {
            console.log(banners); …
Run Code Online (Sandbox Code Playgroud)

angular-services angular-components angular angular-observable

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