我如何从angular2 final(2.0.1)传递简单数据(json)
Posted
技术标签:
【中文标题】我如何从angular2 final(2.0.1)传递简单数据(json)【英文标题】:How can i pass simple data (json) from angular2 final(2.0.1) 【发布时间】:2017-02-14 16:30:01 【问题描述】:这段代码可以在 Angular2 2.0.0.rc.2 上运行,但现在它不起作用 错误。导入 FORM_DIRECTIVES ,HTTP_PROVIDERS ,引导
如何将其修复为 Angular2 v2.0.1
import Component, OnInit from "@angular/core";
import Http, Response, URLSearchParams from "@angular/http";
import FORM_DIRECTIVES from "@angular/common" //error
无法在 Angular v2.0.1 中导入 FORM_DIRECTIVES
import Observable from 'rxjs/Observable';
import IFood from "./food";
import Headers, RequestOptions from "@angular/http";
import "rxjs/Rx";
@Component(
selector: "my-app",
directives: [FORM_DIRECTIVES], //error
templateUrl: "./app/form.html"
)
export class AppComponent implements OnInit
public values: string[];
public headers: Headers;
errorMessage: string;
foods: IFood[];
foodModel = <IFood>;
constructor(private http: Http)
this.http = http;
this.headers = new Headers();
this.headers.append("Content-Type", "application/json");
ngOnInit()
return this.http.get("/home/getdata")
.map((response: Response) => <IFood[]>response.json())
.subscribe(data => this.foods = data, error => this.errorMessage = <any>error);
onSubmit(form): void
let headers = new Headers( "Content-Type": "application/json" );
let options = new RequestOptions( headers: headers );
console.log(this.foodModel);
console.log(JSON.stringify(this.foodModel));
this.http.post("/home/postform", JSON.stringify(this.foodModel), options)
.map((response: Response) => <IFood>response.json())
.subscribe(json => alert(this.foodModel.foodId +" "+ this.foodModel.foodName); /* handle it */ );
在 main.ts 中
import AppComponent from './app.component';
import bootstrap from '@angular/platform-browser-dynamic';
无法导入引导程序
import HTTP_PROVIDERS from '@angular/http'; //error http_providers
无法导入 HTTP_PROVIDERS 引导(AppComponent,[HTTP_PROVIDERS]); //错误引导
如何将其修复为 Angular2 v2.0.1
【问题讨论】:
【参考方案1】:你需要创建NgModule
s
详情见https://angular.io/docs/ts/latest/guide/ngmodule.html
@NgModule(
imports: [BrowserModule, HttpModule, FormsModule, ReativeFormsModule],
declarations: [AppComponent],
bootstrap: [AppComponent]
)
export class AppModule
并更改引导代码
// The browser platform with a compiler
import platformBrowserDynamic from '@angular/platform-browser-dynamic';
// The app module
import AppModule from './app.module';
// Compile and launch the module
platformBrowserDynamic().bootstrapModule(AppModule);
【讨论】:
我的项目中有这个,但是当我更改 angular2 版本时,某些命令不起作用。 抱歉,无法解决“某些命令不起作用”的问题。什么命令?你得到什么错误信息? Angular2 的哪个版本改变了你? 在 app.component.ts 中无法从“@angular/common”导入 FORM_DIRECTIVES 并且无法使用指令:[FORM_DIRECTIVES],FORM_DIRECTIVES
或其他 xxx_DIRECTIVES
或 xxx_PIPES
或 xxx_PROVIDERS
不再存在。您需要导入XxxModule
,如我的回答所示。请阅读我链接到的文档。
如何将数据从控制器传递到前端 angular 2 final以上是关于我如何从angular2 final(2.0.1)传递简单数据(json)的主要内容,如果未能解决你的问题,请参考以下文章
动态加载现有组件 Angular 2 Final Release