(Angular 2 RC4)
使用@HostBinding,我们应该能够修改主机的属性,对吗?我的问题是,这是否也适用于@Input()属性,如果是,那么正确的用法是什么?如果没有,还有另一种方法可以达到这个目的吗?
我在这里做了一个Plunker来说明我的问题:https://embed.plnkr.co/kQEKbT/
假设我有一个自定义组件:
@Component({
selector: 'custom-img',
template: `
<img src="{{src}}">
`
})
export class CustomImgComponent {
@Input() src: string;
}
Run Code Online (Sandbox Code Playgroud)
我想用一个属性指令来提供src属性:
@Directive({
selector: '[srcKey]'
})
export class SrcKeyDirective implements OnChanges {
@Input() srcKey: string;
@HostBinding() src;
ngOnChanges() {
this.src = `https://www.google.com.mt/images/branding/googlelogo/2x/${this.srcKey}_color_272x92dp.png`;
}
}
Run Code Online (Sandbox Code Playgroud)
为什么这个指令不能改变自定义组件的[src]输入属性?
@Component({
selector: 'my-app',
directives: [CustomImgComponent, SrcKeyDirective],
template: `<custom-img [srcKey]="imageKey"></custom-img>`
})
export class AppComponent {
imageKey = "googlelogo";
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
我想缓存和过期来自例如具有某些参数的 GET 请求的 HTTP 响应。
用例示例:
假设我构建了一个这样的服务:
@Injectable()
export class ProductService {
constructor(private http: HttpClient) {}
getProduct$(id: string): Observable<Product> {
return this.http.get<Product>(`${API_URL}/${id}`);
}
getProductA$(id: string): Observable<ProductA> {
return this.getProduct$(id).pipe(
// bunch of complicated operations here
};
}
getProductB$(id: string): Observable<ProductB> {
return this.getProduct$(id).pipe(
// bunch of other complicated operations here
};
}
}
Run Code Online (Sandbox Code Playgroud)
现在无论出于何种原因,在组件 A 中调用函数 A,在组件 B 中调用函数 B。我知道这可以通过另一种方式完成(例如顶级智能组件获取 HTTP 数据并通过输入参数传递它) ,但无论出于何种原因,这两个组件都是“智能”的,它们各自调用一个服务函数。
两个组件都加载在同一页面上,因此会发生两次订阅 = 对同一端点的两次 HTTP 请求 - 即使我们知道结果很可能是相同的。
我想简单地缓存 的响应getProduct$,但我也希望这个缓存很快过期,因为产品管理部门的 Margareth 将在 2 分钟内更改产品价格。
我试过但不起作用:
基本上,我尝试使用 …