RxJS 5 Observable 和 Angular2 http:调用 ajax 一次,保存结果,后续 ajax 调用使用缓存结果

Tha*_*h R 5 javascript ajax rxjs5 angular

下面的代码是我目前拥有的代码的简化版本:

名称.service.ts

@Injectable()
export class NameService {

    const nameURL = "http://www.example.com/name";

    getName() {
        return this.http.get(nameURL);
    }
}
Run Code Online (Sandbox Code Playgroud)

name1.组件.ts

@Component({
    templateUrl: './name1.component.html',
    styleUrls: ['./name1.component.css']
})
export class Name1Component implmenets OnInit {

    private name1;

    constructor(
        private nameService: NameService
    ){}

    ngOnInit() {
        this.setupName();
    }

    private setupName() {

        this.nameService.getName()
            .subscribe(
                resp => this.name1 = resp,
                error => this.name1 = "unknown"
            );
    }
}
Run Code Online (Sandbox Code Playgroud)

name2.component.ts

@Component({
    templateUrl: './name2.component.html',
    styleUrls: ['./name2.component.css']
})
export class Name2Component implmenets OnInit {

    private name2;

    constructor(
        private nameService: NameService
    ){}

    ngOnInit() {
        this.setupName();
    }

    private setupName() {

        this.nameService.getName()
            .subscribe(
                resp => this.name2 = resp,
                error => this.name2 = "unknown"
            );
    }
}
Run Code Online (Sandbox Code Playgroud)

这就是我想要做的,name1.component.ts首先调用类getName的方法NameServicegetName然后将进行 ajax 调用并返回一个 observable。

接下来,name2.component.ts还将调用getName该类的相同方法NameService,并且getName还将执行相同的 ajax 调用并返回一个 observable。

是否可以使用 rxjs,getName方法 inNameService进行第一次 ajax 调用时,它会存储 ajax 调用的结果。对该getName方法的任何后续函数调用都将返回第一个 ajax 调用的缓存结果,并且不会执行另一个冗余的 ajax。

Nuv*_*nda 4

您可以多次订阅 Observable,因此,如果您只想保存第二个网络请求以获取两个组件之间共享的数据,则可以将其缓存在您的服务中,如下所示:

@Injectable()
export class NameService {

    const nameURL = "http://www.example.com/name";
    private cache: Observable<any>;

    getName() {
        return this.cache || this.cache = this.http.get(nameURL);
    }
}
Run Code Online (Sandbox Code Playgroud)