学习Angular2 TypeScript2:共享类

时间:2016-11-08 23:54:19

标签: angular ionic2 typescript2.0

我是一名全新的Angular2和TypeScript..well的网络开发人员,一般都是应用程序的新手。

我正在尝试设置一个共享类,我的各种对象可以从中获取用户数据,例如SessionID。我的问题是我不知道如何获得可以执行HTTP请求的构造函数。

我在Visual Code中使用Ionic2,所以使用Angular2和Typescript。我开始使用离子为我构建一个模板,并且我没有在Visual Code中获得错误,但是在我运行"离子服务 - 地址192.168.1.128"

后得到以下错误
  

未捕获错误:在CurrentUser上找不到指令注释       在DirectiveResolver.resolve(http://192.168.1.128:8100/build/main.js:23898:19)       在CompileMetadataResolver.getDirectiveMetadata(http://192.168.1.128:8100/build/main.js:24885:51)       at RuntimeCompiler._createCompiledHostTemplate(http://192.168.1.128:8100/build/main.js:39289:51)       在http://192.168.1.128:8100/build/main.js:39246:37       at Array.forEach(native)       在http://192.168.1.128:8100/build/main.js:39245:45       at Array.forEach(native)       在RuntimeCompiler._compileComponents(http://192.168.1.128:8100/build/main.js:39236:43)       at RuntimeCompiler._compileModuleAndComponents(http://192.168.1.128:8100/build/main.js:39173:37)       在RuntimeCompiler.compileModuleAsync(http://192.168.1.128:8100/build/main.js:39164:21

由于我的理解很少,我认为这个问题的重要参与者是:

  • /src/app/app.compnonent.ts
  • /src/app/app.module.ts
  • /src/app/service/currentuser.ts
  • /tsconfig.json
  • /package.json

如果我是对的,那些文件就在下面。

那么如何才能将传递给该HTTP对象的CurrentUser类转换为它?我做错了什么?

app.compnonent.ts

import { Component, ViewChild } from '@angular/core';
import { Nav, NavController, Platform } from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';

import { TabsPage } from '../pages/tabs/tabs';
import { CurrentUser } from './service/currentUser';

@Component({
  templateUrl: 'app.html',
  providers: [CurrentUser]
})
export class MyApp {
  @ViewChild(Nav) nav: Nav;

  rootPage = TabsPage;

  constructor(platform: Platform, public _user: CurrentUser, private _navCtrl: NavController) {
    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      StatusBar.styleDefault();
      Splashscreen.hide();
      if (!_user.sessionId) {
        _navCtrl.push("login.html");
      }
    });
  }
}

app.module.ts

import { CurrentUser } from './service/currentUser';
import { NgModule } from '@angular/core';
import { IonicApp, IonicModule } from 'ionic-angular';

import { MyApp } from './app.component';
import { AboutPage } from '../pages/about/about';
import { ContactPage } from '../pages/contact/contact';
import { HomePage } from '../pages/home/home';
import { LoginPage } from '../pages/login/login';
import { TabsPage } from '../pages/tabs/tabs';

@NgModule({
  declarations: [
    MyApp,
    AboutPage,
    ContactPage,
    HomePage,
    LoginPage,
    TabsPage
  ],
  imports: [
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp, CurrentUser],
  entryComponents: [
    MyApp,
    AboutPage,
    ContactPage,
    HomePage,
    LoginPage,
    TabsPage
  ],
  providers: [CurrentUser]
})
export class AppModule {}

currentUser.ts

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';

@Injectable()
export class CurrentUser {
  public sessionId: string;
  private local: Storage;

  constructor(private _http: Http) {
    this.local = new Storage();
    if (this.local.getItem("user-profile")) {
      var profile = JSON.parse(this.local.getItem("user-profile"));
      this.sessionId = profile.sessionId;
    } else {
      this.sessionId = null;
    }
  }

  public login(email: string, password: string) {
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    return new Promise((resolve, reject) => {
    this._http.get("http://example.com/svc/rest.php?action=login&email=" + email + "&password=" + password, options)
      .subscribe((data) => {
        console.log(data);
      });
    });
  }
  public create(email: string, password: string, name: string) {
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    return new Promise((resolve, reject) => {
    this._http.post("http://example.com/svc/rest.php", { action: "user", email: email, password: password, name: name}, options)
      .subscribe((data) => {
        console.log(data);
      });
    });
  }
}

tsconfig.json

{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "declaration": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [
      "dom",
      "es2015"
    ],
    "module": "es2015",
    "moduleResolution": "node",
    "sourceMap": true,
    "target": "es5"
  },
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "node_modules"
  ],
  "compileOnSave": false,
  "atom": {
    "rewriteTsconfig": false
  }
}

的package.json

{
  "name": "example",
  "author": "Wade McDaniel",
  "homepage": "http://example.com/",
  "private": true,
  "scripts": {
    "build": "ionic-app-scripts build",
    "watch": "ionic-app-scripts watch",
    "serve:before": "watch",
    "emulate:before": "build",
    "deploy:before": "build",
    "build:before": "build",
    "run:before": "build"
  },
  "dependencies": {
    "@angular/common": "2.0.0",
    "@angular/compiler": "2.0.0",
    "@angular/compiler-cli": "0.6.2",
    "@angular/core": "2.0.0",
    "@angular/forms": "2.0.0",
    "@angular/http": "2.0.0",
    "@angular/platform-browser": "2.0.0",
    "@angular/platform-browser-dynamic": "2.0.0",
    "@angular/platform-server": "2.0.0",
    "@ionic/storage": "1.1.6",
    "ionic-angular": "2.0.0-rc.1",
    "ionic-native": "2.2.3",
    "ionicons": "3.0.0",
    "rxjs": "5.0.0-beta.12",
    "zone.js": "0.6.21"
  },
  "devDependencies": {
    "@ionic/app-scripts": "0.0.38",
    "typescript": "2.0.6"
  },
  "description": "example app",
  "cordovaPlugins": [
    "cordova-plugin-device",
    "cordova-plugin-console",
    "cordova-plugin-whitelist",
    "cordova-plugin-splashscreen",
    "cordova-plugin-statusbar",
    "ionic-plugin-keyboard"
  ],
  "cordovaPlatforms": []
}

谢谢!

更新 事实证明,Storage()使CurrentUser构造函数无效。请参阅下面的评论。谢谢silentsod!

现在弄清楚如何从CurrentUser获取存储......

1 个答案:

答案 0 :(得分:2)

不要引导CurrentUser,bootstrapping正在设置条目组件,而CurrentUser是共享服务,它不是条目组件。

以下是文档:https://angular.io/docs/ts/latest/cookbook/ngmodule-faq.html#!#q-entry-component-defined

  

Angular按类型强制加载的任何组件都是一个条目   部件,

     

通过其选择器以声明方式加载的组件不是条目   成分

     

< ...>

     

大多数应用程序开发人员不需要添加组件   entryComponents。

您还问了一个关于Http在您的构造函数中可用的问题。在你的app.module.ts中你应该这样做:

import { HttpModule } from "@angular/http";

@NgModule({
<...>
imports: [<...>, HttpModule]
})

这将实例化一个Http提供程序,供您随意注入。