小编Tha*_*h R的帖子

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

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

名称.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() …
Run Code Online (Sandbox Code Playgroud)

javascript ajax rxjs5 angular

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

标签 统计

ajax ×1

angular ×1

javascript ×1

rxjs5 ×1