Post 使用Angular 2服务向数据库添加数据,UI不刷新

Post 使用Angular 2服务向数据库添加数据,UI不刷新,post,service,angular,Post,Service,Angular,第一次来这里…温柔点。我已经搜索了很多次,没有找到任何能解决这个问题的东西。我们已采用Angular2进行单页应用。我有一个页面,它有一个数据输入块,下面有一个网格。页面在加载时调用“get”服务填充网格。单击数据输入区域中的submit按钮调用一个“add”服务,该服务执行一个存储过程并将数据插入postgre sql数据库。一切都好。除此之外,我正在努力使网格刷新以显示新添加的行(甚至尝试在“添加”之后调用“get”服务)。到目前为止,我看到的所有示例都只使用本地数组作为数据存储(pop、p

第一次来这里…温柔点。我已经搜索了很多次,没有找到任何能解决这个问题的东西。我们已采用Angular2进行单页应用。我有一个页面,它有一个数据输入块,下面有一个网格。页面在加载时调用“get”服务填充网格。单击数据输入区域中的submit按钮调用一个“add”服务,该服务执行一个存储过程并将数据插入postgre sql数据库。一切都好。除此之外,我正在努力使网格刷新以显示新添加的行(甚至尝试在“添加”之后调用“get”服务)。到目前为止,我看到的所有示例都只使用本地数组作为数据存储(pop、push操作数据)。由于我们的数据被持久保存在数据库中,这些示例并不能让我完全理解。IContent是一个为数据建模的接口_contentList是一个IContent数组,由“Get”服务填充。感谢您的帮助

更新:根据JB的建议,我注释掉了get服务中的缓存代码,并在add>service调用之后添加了对get服务的显式调用。还是有同样的行为

主要组成部分:

import {Component}     from 'angular2/core';
import {IContent} from '../../classes/interfaces';
import {ContentService} from '../../services/content.service';
...
import {OnInit} from 'angular2/core';
import {ControlGroup, FormBuilder, Validators} from 'angular2/common';
import {Observable} from 'rxjs/Observable';


@Component({
    selector: 'view',
    templateUrl: 'src/views/the-view.html',
    providers: [ContentService],
    directives: [ROUTER_DIRECTIVES, MdToolbar, MdButton, MdCard, MD_LIST_DIRECTIVES, MdInput],
})

export class ContentMgmtComponent {

    public _contentList: IContent[];
    myForm: ControlGroup;
    contentAdded: boolean = false;


        constructor(private _formBuilder: FormBuilder, private _contentService: ContentService) {

        // Programmatically build out form
        this.myForm = _formBuilder.group(
            {
                pageID: ["", Validators.compose([Validators.required])],
                zoneID: ["", Validators.required],
                contentText: ["", Validators.compose([Validators.required, Validators.maxLength(10)])],
                startDate: ["", Validators.required],
                endDate: ["", Validators.required]
        });

        // Get existing pages / content 
        this._contentService.getAllContent()
            .subscribe((content: IContent[]) => {
                this._contentList = content[0]["contentInfo"];
            });


    }

    //Add the new content to the database.
    onAddContentClick(pageId: string, zoneId: string, contentText: string, startDate: string, endDate: string) {

        this._contentService.addContent(pageId, zoneId, contentText, startDate, endDate)
        this.contentAdded = true;

        // *** PROBLEM BE HERE ... tried calling the Get Service, etc. ***


    }

 }
应刷新的-view.html部分:

<div class="panel panel-primary">
    <div class="panel-heading"><h4>Nova Custom Content Manager</h4>    </div>
    <div class="panel-body">
        <table class="col-md-12 table-bordered table-striped table-hover table-condensed">
            <thead>
                <tr>
                    <th>Content Id</th>
                    <th>Page Id</th>
                    <th>Zone Id</th>
                    <th>Content</th>
                    <th>Active FL</th>
                    <th>Start Date</th>
                    <th>End Date</th>
                </tr>
            </thead>
            <tbody>
                <tr class="info" *ngFor="#contentItem of _contentList">
                    <td>{{contentItem.contentID}}</td>
                    <td>{{contentItem.pageID}}</td>
                    <td>{{contentItem.zoneID}}</td>
                    <td>{{contentItem.contentText}}</td>
                    <td>{{contentItem.activeFlag}}</td>
                    <td>{{contentItem.startDate}}</td>
                    <td>{{contentItem.endDate}}</td>
                </tr>
            </tbody>
        </table>
    </div>

Nova自定义内容管理器
内容Id
页面Id
区域Id
内容
活性荧光粉
开始日期
结束日期
{{contentItem.contentID}
{{contentItem.pageID}
{{contentItem.zoneID}
{{contentItem.contentText}
{{contentItem.activeFlag}
{{contentItem.startDate}
{{contentItem.endDate}

服务:

import {Injectable} from 'angular2/core';
import {Http, Response, Headers, RequestOptions, URLSearchParams} from 'angular2/http';
import {Observable} from 'rxjs/Rx';
import {IContent} from '../classes/interfaces';
import {Observer} from 'rxjs/Observer';


@Injectable()
export class ContentService {

    content: IContent[];    //returned by the actual service call to the consumer


    constructor(private http: Http) { 
    }

    addContent(_pageId: string, _zoneId: string, _content: string, _startDate: string, _endDate: string) {
        let body = JSON.stringify({ pageID: _pageId, zoneID: _zoneId, contentText: _content, activeFlag: "true", startDate: _startDate, endDate: _endDate });
        let headers = new Headers({ 'content-type': 'application/json' });
        let options = new RequestOptions({ headers: headers });

        this.http.post('http://whereever.com/api/addcontent', body, options)
            .subscribe(
            data => console.log(data),
            err => console.log(err.json().message),
            () => console.log('Authentication Complete')
        );
    }

    getAllContent(): Observable<IContent[]> {
        if (!this.content) {
            //return this.http.get("/src/services/content.json")
            return     this.http.get("http://whereever.com/api/getallcontents")
                .map((res: Response) => {
                    this.content = res.json();
                    return this.content;
                })
                .catch(this.handleError);
        }
        else {
            //return cached data
            return this.createObservable(this.content);
        }
    }

    private extractData(res: Response) {
        if (res.status < 200 || res.status >= 300) {
          throw new Error('Bad response status: ' + res.status);
        }
        let body = res.json();
        return body.data || { };
    }

**strong text**...


}
从'angular2/core'导入{Injectable};
从'angular2/Http'导入{Http、响应、头、请求选项、URLSearchParams};
从'rxjs/Rx'导入{Observable};
从“../classes/interfaces”导入{IContent};
从'rxjs/Observer'导入{Observer};
@可注射()
导出类内容服务{
内容:IContent[];//由实际服务调用返回给使用者
构造函数(专用http:http){
}
addContent(_pageId:string,_zoneId:string,_content:string,_startDate:string,_endDate:string){
让body=JSON.stringify({pageID:_pageID,zoneID:_zoneID,contentText:_content,activeFlag:“true”,startDate:_startDate,endDate:_endDate});
let headers=新的头({'content-type':'application/json'});
let options=newrequestoptions({headers:headers});
this.http.post('http://whereever.com/api/addcontent,正文,选项)
.订阅(
data=>console.log(数据),
err=>console.log(err.json().message),
()=>console.log('Authentication Complete')
);
}
getAllContent():可观察{
如果(!this.content){
//返回此.http.get(“/src/services/content.json”)
返回此.http.get(“http://whereever.com/api/getallcontents")
.map((res:Response)=>{
this.content=res.json();
返回此.content;
})
.接住(这个.把手错误);
}
否则{
//返回缓存数据
返回this.createObservable(this.content);
}
}
私有数据(res:Response){
如果(分辨率状态<200 | |分辨率状态>=300){
抛出新错误(“错误响应状态:”+res.status);
}
让body=res.json();
返回body.data |{};
}
**强文本**。。。
}

您的服务返回缓存数据。不应该


让它在每次调用时发出http请求,而不仅仅是第一次。否则,显然,它总是返回相同的过时数据。

您的服务返回缓存数据。不应该


让它在每次调用时发出http请求,而不仅仅是第一次。否则,很明显,它总是返回相同的、过时的数据。

只是一个偶然的机会,但您正在从服务返回的内容列表中替换您的内容列表。也许可以尝试清除绑定列表并添加从服务返回的内容。我假设,如果用一个新实例替换整个列表,那么对列表的绑定将不起作用


此。_contentList=content[0][“contentInfo”];//清除此项。_contentList并从内容[0][“contentInfo”]

重建它只是一个偶然的机会,但您正在从服务返回的内容列表替换您的内容列表。也许可以尝试清除绑定列表并添加从服务返回的内容。我假设,如果用一个新实例替换整个列表,那么对列表的绑定将不起作用


此。_contentList=content[0][“contentInfo”];//清除此选项。_contentList并从内容[0][“contentInfo”]

JB:即使我在Get中注释掉缓存代码,它在添加后仍然不会刷新…即使在添加后显式调用Get。然后用更新的代码更新您的问题。可能还有其他问题。您仍在返回缓存数据。发完邮件后,控制员仍然不给你打电话。删除服务中的
内容
字段。删除方法中的if/else。添加用于刷新数据的代码。这就是问题所在。提示:您必须在帖子成功后刷新数据。JB:即使我在Get中注释掉缓存代码,它在添加后仍然不会刷新…即使在添加后显式调用Get。然后更新您的问题w