2

我正在尝试 5 分钟的 Anuglar2 教程,当它说您可以使用外部模板时,我尝试了它。

我的组件看起来像这样

import {Component, Template, bootstrap} from 'angular2/angular2';

// Annotation section
@Component({
  selector: 'my-app'
})
@Template({
  url: "component.html"
})
// Component controller
class MyAppComponent {
  constructor() {
    this.name = 'Alice';
  }
}

bootstrap(MyAppComponent);

我的外部模板出错并修复了它,但 HTML 文件仍然被缓存,所以我无法在浏览器中使用效果。

弄清楚他们是如何缓存它的,我查看了Github上的代码

我找到了这个

#angular/modules/angular2/src/core/compiler/template_loader.js

@Injectable()
export class TemplateLoader {
  _xhr: XHR;
  _htmlCache: StringMap;
  _baseUrls: Map<Type, string>;
  _urlCache: Map<Type, string>;
  _urlResolver: UrlResolver;

  constructor(xhr: XHR, urlResolver: UrlResolver) {
    this._xhr = xhr;
    this._urlResolver = urlResolver;
    this._htmlCache = StringMapWrapper.create();
    this._baseUrls = MapWrapper.create();
    this._urlCache = MapWrapper.create();
  }

  // TODO(vicb): union type: return an Element or a Promise<Element>
  load(template: Template) {
    if (isPresent(template.inline)) {
      return DOM.createTemplate(template.inline);
    }

    if (isPresent(template.url)) {
      var url = this.getTemplateUrl(template);
      var promise = StringMapWrapper.get(this._htmlCache, url);

      if (isBlank(promise)) {
        promise = this._xhr.get(url).then(function (html) {
          var template = DOM.createTemplate(html);
          return template;
        });
        StringMapWrapper.set(this._htmlCache, url, promise);
      }

      return promise;
    }

所以我检查了 StringMapWrapper angular/modules/angular2/src/facade/collection.es6

并且设置代码只是

static set(map, key, value) {
    map[key] = value;
  }

我看到 StringMapWrapper 来自全球

export var StringMap = global.Object;

但是查看angular/modules/angular2/src/facade/lang.es6 我无法弄清楚地图的缓存位置。

我对缓存过程知之甚少,希望有人能解释在这种情况下他们是如何做到的。

4

2 回答 2

0

StringMapWrapper.create()创建一个对象字面量{}。他们使用类似StringMapWrapperDart 支持的东西,其中这些原语在其他语言中以不同方式创建。简而言之,他们所做的就是这个

var cache = {};
xhr(templateUrl).then(template => {
  cache[templateUrl] = template;
  return template;
})
于 2015-09-22T06:37:04.620 回答
0

@gdi2290 几乎回答了您的问题,如果您想了解更多关于 JavaScript/TypeScript 中的缓存管理的信息,请在此处查看我的帖子http://www.ravinderpayal.com/blogs/12Jan2017-Ajax-Cache-Mangement-Angular2-服务.html

有一个缓存管理类的逐步解释,它充当 AJAX 的层,并且可以作为服务注入到组件中。这是类代码的概要:-

 private loadPostCache(link:string){
     if(!this.loading[link]){
               this.loading[link]=true;
               this.links[link].forEach(a=>this.dataObserver[a].next(false));
               this.http.get(link)
                   .map(this.setValue)
                   .catch(this.handleError).subscribe(
                   values => {
                       this.data[link] = values;
                       delete this.loading[link];
                       this.links[link].forEach(a=>this.dataObserver[a].next(false));
                   },
                   error => {
                       delete this.loading[link];
                   }
               );
           }
    }

    private setValue(res: Response) {
        return res.json() || { };
    }

    private handleError (error: Response | any) {
        // In a real world app, we might use a remote logging infrastructure
        let errMsg: string;
        if (error instanceof Response) {
            const body = error.json() || '';
            const err = body.error || JSON.stringify(body);
            errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
        } else {
            errMsg = error.message ? error.message : error.toString();
        }
        console.error(errMsg);
        return Observable.throw(errMsg);
    }

    postCache(link:string): Observable<Object>{

         return Observable.create(observer=> {
             if(this.data.hasOwnProperty(link)){
                 observer.next(this.data[link]);
             }
             else{
                 let _observable=Observable.create(_observer=>{
                     this.counter=this.counter+1;
                     this.dataObserver[this.counter]=_observer;
                     this.links.hasOwnProperty(link)?this.links[link].push(this.counter):(this.links[link]=[this.counter]);
                     _observer.next(false);
                 });
                 this.loadPostCache(link);
                 _observable.subscribe(status=>{
                     if(status){
                         observer.next(this.data[link]);
                     }
                     }
                 );
             }
            });
        }
于 2017-01-12T13:57:35.587 回答