我正在使用Stroustrup(Programming Principles&Practice Using C++)一书学习C++.在练习中,我们定义了一个简单的结构:
template<typename T>
struct S {
explicit S(T v):val{v} { };
T& get();
const T& get() const;
void set(T v);
void read_val(T& v);
T& operator=(const T& t); // deep copy assignment
private:
T val;
};
Run Code Online (Sandbox Code Playgroud)
然后我们要求定义一个const和一个非const成员函数来获取val.
我想知道:有任何情况下get,返回非const 函数是否有意义val?
对我来说似乎更清洁,我们无法间接改变这种情况下的价值.在需要const和非const get函数返回成员变量的情况下可能会出现什么情况?
我目前正在学习 Angular5 和 RxJS。我正在尝试运行一个简单的应用程序:
我尝试了两个选项,每个选项都有一个问题:
a) 订阅组件并更新模板数据:
this.placePredictionService.getPlacePredictions(term).subscribe( data =>
{
this.results = data;
});
Run Code Online (Sandbox Code Playgroud)
模板会在 {{results}} 绑定上更新,但仅在第二个函数调用时更新。然后使用第一次调用的结果更新模板。为什么?
b) 使用异步管道返回可观察和更新模板
private results$: Observable<any[]>;
this.results$ = this.placePredictionService.getPlacePredictions(term);
Run Code Online (Sandbox Code Playgroud)
这样,模板中不会发生任何事情。我不明白什么?我的理解欠缺什么?非常感谢您提供有关调查内容的提示。
两个问题的解决方案:谢谢@Richard Matsen!
a) 问题是,Google Maps API 的调用不在 Angular Zone 内,因此未自动触发更改检测。将 API 调用包装在 ngZone.run() 函数中的服务中可以解决问题:
this.autocompleteService.getPlacePredictions({input: term}, data => {
this.ngZone.run(() => {
this.predictions.next(data);
});
});
Run Code Online (Sandbox Code Playgroud)
b) 使用主题不会在每次新击键时产生新流解决了异步管道无法正常工作的问题,请参阅下面的代码注释。
完整的组件、服务和模板是这样的:
app.component.ts
import { Component } from '@angular/core';
import { MapsAPILoader } …Run Code Online (Sandbox Code Playgroud) 我正在Angular 5项目上工作,并希望通过@ angular / service-worker包提供PWA功能。
我无法缓存和服务Google Maps API请求(例如,图块)。联机时不会缓存响应,因此脱机时也不会提供响应。
我试过的
将Maps URL添加到dataGroups:脱机时没有错误,但是也没有缓存,出现以下错误:
错误错误:未捕获(承诺):事件:{“ isTrusted”:true}(在main.bundle.js中)
将Maps URL添加到assetGroups installMode:prefetch,尝试进行预取时出现跨域错误:
所请求的资源上没有“ Access-Control-Allow-Origin”标头。因此,不允许访问源' http:// localhost:8080 '。如果不透明的响应满足您的需求,请将请求的模式设置为“ no-cors”,以在禁用CORS的情况下获取资源。
将Maps URL添加到assetGroups installMode:lazy,得到的结果与installMode:prefetch相同
其余数据缓存并运行良好(从localhost的localhost和localhost的json静态返回到其他端口)。
我的ngsw-config.json看起来像这样:高度赞赏任何指针。
{
"index": "/index.html",
"assetGroups": [{
"name": "app",
"installMode": "prefetch",
"resources": {
"files": [
"/favicon.png",
"/index.html"
],
"versionedFiles": [
"/*.bundle.css",
"/*.bundle.js",
"/*.chunk.js"
],
"urls": [
"https://fonts.googleapis.com/css?family=Roboto:300,400,500,700",
"https://fonts.gstatic.com/s/roboto/v18/KFOlCnqEu92Fr1MmEU9fBBc4AMP6lQ.woff2",
"https://fonts.gstatic.com/s/roboto/v18/KFOmCnqEu92Fr1Mu4mxKKTU1Kg.woff2"
]
}
}, {
"name": "assets",
"installMode": "lazy",
"updateMode": "prefetch",
"resources": {
"files": [
"/assets/**"
]
}
}],
"dataGroups": [{
"name": "from-api",
"urls": [
"/api/restaurants",
"/img/**", …Run Code Online (Sandbox Code Playgroud) google-maps google-maps-api-3 service-worker angular angular-service-worker