30 July 2019
Angular (45) -- Angular Universal
by Jerry Zhang
LeetCode Day 25: P171. Excel Sheet Column Number (Easy)
题目:
给一个字母形式的Excel列号,求它的数字形式的列号:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
思路:
从最后一位开始(最右边的一位字母),第一位是26的零次方乘以这个字母表示的数字,第二位是26的一次方乘以这个字母表示的数字。
我的代码:
public class E_171_ExcelSheetColumnNumber {
public static int titleToNumber(String s) {
char[] chars = s.toCharArray();
int result = 0;
int pow26 = 1;
for (int i = chars.length - 1; i >=0; i--) {
int n = chars[i] - 'A' + 1;
result += pow26 * n;
pow26 *= 26;
}
return result;
}
public static void main(String[] args) {
int b = titleToNumber("ZY");
System.out.println(b);
}
}
这道题比上一道简单多了,因为没有字母转换的麻烦。
最优解:
class Solution {
public int titleToNumber(String s) {
int res=0;
char[] ar = s.toCharArray();
for(int i=0;i<ar.length;i++){
int power = ar.length-i-1;
res += Math.pow(26, power) *(ar[i]-'A'+1);
}
return res;
}
}
跟我的非常类似了,只不过我不想用Math.pow,所以手工每次乘以26
Angular:
Angular Universal
Pre-render an angular app on the server.
ng add @nguniversal/express-engine --clientProject RecipeBook
In the app.server.module.ts, make sure you have
import { ModuleMapLoaderModule } from '@nguniversal/module-map-ngfactory-loader';
If this was not set up, we can install it manually.
npm install --save @nguniversal/module-map-ngfactory-loader
This module enables lazy loading with angular universal.
Now, the code is first rendered and executed on the server, not in the browser.
But the localStorage
is not available on the server, because it’s in the browser.
To fix this, we need to go to the app.component.ts
file, where we dispatch the AutoLogin
action, and make sure we
DO NOT dispatch it when this get rendered on the server.
So we need to know whether it is running on a server or not. We inject a global constant, PLATFORM_ID
.
constructor(
private store: Store<fromApp.AppState>,
private loggingService: LoggingService,
@Inject(PLATFORM_ID) private platformId
) {}
Then, we can check isPlatformBrowser
ngOnInit(): void {
if (isPlatformBrowser(this.platformId)) {
this.store.dispatch(new AuthActions.AutoLogin());
}
this.loggingService.printLog('Hello from AppComponent ngOnInit');
}
Then, in the package.json
file, we can find "build:ssr"
. So we can use
npm run build:ssr
This will build our app for angular universal.
Now we need a server where can run nodeJs. We need to upload the whole project on the server and can use the command
npm run serve:ssr
Conclusion:
You need a host that does - for example AWS ElasticBeanstalk or Heroku.
To these hosts, you need to upload your dist/ folder along with the package.json file. On the web server, you then have to ensure that npm install is executed, followed by npm serve:ssr.
tags: Angular